As some of my scripts have really started to grow, and often include some rather large datasets residing in variables, I noticed that the system would bog down after a while from all the memory in use. Simple enough, I thought, I’ll just get rid of those variables with Remove-Variable. Great in concept; but it doesn’t affect memory usage at all.
A little digging showed that PowerShell is not so great at Garbage Collection; it apparently waits to Collect until it needs to, and never seems to think it needs to. Great. Fortunately, it has direct access to .NET functions, so you can just run Garbage Collection with:
[gc]::Collect()
This has the nice benefit of speeding up your system, but it can take a while to run. So I added a simple Function to my functions.ps1 file which will allow me to run this when it’s needed:
function Clean {
foreach ($arg in $args) {
Remove-Variable $arg -Scope script
}
[gc]::Collect()
}
You can send any number of variables to this function, but, like using Remove-Variable alone, you have to send it variables names without the leading “$”. (If you wonder why, run Get-Variable and look at the variable names, or consider the difference between “$variable” and ‘variable’.) It will remove all those variables, then run garbage collection. Not quite an everyday command, but useful after working with large datasets or other memory hogs.