How can I diagnose which of my PowerShell variables/resources are eating memory?

Viewed 88

I have a complex PowerShell module which polls a bunch of machines for data, munges it, and outputs a CSV. It works great... until I run it across 1000-4000 machines. After a certain point it gradually, but noticeably slows and memory use rises into the 1-4GB range.

After the module has finished running and returns shell control to me, the session retains all of that reserved memory. I didn't realize that variables from the module would persist after the module completed, but running Get-Variable shows me I was mistaken.

I've tried removing all of the suspect variables with Remove-Variable, while watching Task Manager, and that had no effect. Similarly the few background jobs that somehow remained (even though I'm always using Remove-Job) didn't seem to be causing the problem, after manually removing them. However running [System.GC]::Collect() did release all of the excess memory.

Is there any way I can get a list of variables/resources within a session and their relative size in memory? Or any other way of easily diagnosing where this "memory leak" is, so that I can try to identify where in the script I can release certain data to optimize performance? I don't like the idea of trying to integrate forced garbage collection, but I'm blind as to what it's doing to solve the issue.

0 Answers
Related