I’m often running too many applications on my workstation, and at least one session of  PowerShell is almost always open.  I’m regularly jumping back to a PowerShell prompt to try something out, query something from my database, or complete a task. 

If I don’t clear out the variables that reference objects I’m done with, the amount of memory used by my PowerShell session increases dramatically, which impacts some other applications that I run.  (I know, memory is cheap.. buy more memory.  I’ve got a limited budget and I have to prioritize.)

So I’ve written a couple of functions that can help me clear out the extraneous variables and free up some of that memory being used by PowerShell.

The first function (and I’m open to suggestions on the naming here..), saves them to the AppDomain (so I don’t lose them when I clear out variables).  I recommend running this shortly after starting PowerShell or running it from your profile.

Later, when I’m feeling some memory pressure, I can run the second function Remove-NewVariable, which calls Remove-Variable for all variables whose names I did not save in the AppDomain.  This removes the references to the objects they represented. 

Info Overload: Notice that I said that it removed the references to those objects.  Those objects still exist in memory and remain there until the CLR “garbage collects” them, releasing that memory.  The CLR has a process to reclaim that “used” memory when there is a need to reuse it or when it is impacting other performance.

Even if you skipped the previous bold section (which is perfectly acceptable), you might have noticed that when you clear out a variable, your memory usage for PowerShell might remain high for a while.  My function speeds up the natural “garbage collection” process by calling [System.GC]::Collect(), forcing the CLR to reclaim that memory.

There are a couple of “helper” functions included, Get-SessionVariableList, which will list out the variable names saved, in case you wanted to see which variables were going to be left and Add-SessionVariable, which adds more values to the current list. 

 

Feedback and improvements are always welcome!

PSMDTAG:FAQ Memory