Category Archives: Microsoft

Powershell garbage collection

Today one of my scripts at work was consuming lots of memory. Turns out that Powershell doesn’t handle garbage collection very well, it only runs on the completion of a script, however if you have a script that is in a continuous loop, garbage collection will not happen. Here is a handy hint to anyone writing scripts that don’t quit on how to force Powershell garbage collection.

powershell garbage collection

Simply add the following line of code in your ‘leaking’ foreach or while loop

while(…) {

[System.GC]::Collect()

}

I have to give credit to Dmitry Sotnikov as he stumbled on this issue a few months ago and solved it.

Once I had done this, my script was no longer consuming lots of memory. Win!