Freeing up memory in PowerShell using garbage collector

Just got this great tip from Lars on how he reduces memory consumption in his AD PowerShell scripts with a simple garbage collection call (basically explicitly telling .NET behind PowerShell to recycle the objects no longer in use):

Using Quest AD tools I often run in to memory consumption problems. I thought it was a question of memoryleaks, but its not, its the Garbage collection that doesn’t get collection until its to late.
So i’m using this when I use Quests AD Management Cmdlets in PowerShell, where $i is a simple counter

if (($i % 200) -eq 0)
{
[System.GC]::Collect()
}

Hope that helps!

4 Responses to “Freeing up memory in PowerShell using garbage collector”


  1. 1 Kelvin Wong February 25, 2012 at 6:45 pm

    Reblogged this on Salt * Wet * Bytes and commented:
    Something new and useful to remember🙂

  2. 2 Ashutosh February 29, 2012 at 9:29 am

    Explicitly calling Garbge collector is not a good idea generally. The garbace collector is optimized to run at specific intervals depending on memory usage. Manually calling the GC disturbs the calculation,

    • 3 Dmitry Sotnikov February 29, 2012 at 3:14 pm

      Indeed one should use caution: in your particular case resulting performance may get better or worse. In this particular situation though, one of the users reported that he is getting much lower memory consumption when in between his AD management with PowerShell inside PowerGUI Script Editor he is using garbage collection calls – so I wanted to pass the knowledge.


  1. 1 PoSH Garbage Collection « Lange's Tech Musings Trackback on February 29, 2012 at 8:04 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




My Recent Tweets

Legal

The posts on this blog are provided “as is” with no warranties and confer no rights. The opinions expressed on this site are mine and mine alone, and do not necessarily represent those of my employer - WSO2 or anyone else for that matter. All trademarks acknowledged.

© 2007-2014 Dmitry Sotnikov

February 2012
M T W T F S S
« Jan   Mar »
 12345
6789101112
13141516171819
20212223242526
272829  

%d bloggers like this: