r/PowerShell • u/Guilty-Act-4991 • Oct 12 '26
Question Parallel thread disposing?
Hey got a wierd issue or its by desing not sure but when I run
$computers | foreach-object -parallel {
$vmobject = Get-VM $_
$ram = $vmobject.MemoryGB
$CPU = $vmobject.numCPU
$HDD = $_ | get-harddisk
} lets say I run in against 500 computers when that happens powershell will spike cpu on machine that this command is ran and keeps increasing ram usage which is understandable but problem is even when command is done ram usage stays high untill powershell window is close. Is there something I am missing or is there some method to dispose of parallel runspace manually?
Thanks for advice
EDIT: The code itself is not important , the behaviour of parallel scripblock itself is my question and why doesnt it free up RAM after code has ran successfully
5
u/raip Oct 12 '26
There was a previous bug, that I believe was fixed, where the garbage collector wasn't getting scheduled to free the memory in heavily parallelized runs and would cause OOM exceptions even on reasonable datasets. You can use this to free the memory correctly. I remember having to batch jobs pretty aggressively and then a collect after every batch to keep things running smooth.
5
u/PinchesTheCrab Oct 12 '26 edited Oct 12 '26
I don't think this is doing what you want it to do - it's just overwriting these variables over and over again. No data except the very last VM is being captured.
Also PowerCli is very performant and I'd tinker a bit with the module's functionality before multi-threading it. I'd be worried about hammering vsphere or whatever by trying to multi-thread something like this.
Does this approach work?
2
u/Onrawi Oct 12 '26
Yeah everything it picks up will stay until garbage collection determines it isn't needed anymore. Might want to separate it out into a Start-Job or something that has its own run space that goes away when it closes out.
2
u/thomsxD Oct 12 '26
You are invoking Get-HardDisk which is kind of heavy if run against 500 computers.
You could look into a faster one by avoiding it and use ExtensionData instead.
1
u/BlackV Oct 12 '26
I guess this is vmware powercli, I didnt recognise
get-harddiskhave you looked at the
-ThrottleLimitparameter on that?I also assume this i not your actual code cause you dont output anything here anyway
If you are actually querying 500 Vms, it might be better to use the rest API at that point
3
u/Kreout Oct 13 '26
A high working set after the loop is not, by itself, proof that runspaces leaked. I would compare a few identical passes in the same PowerShell process: does memory settle at a plateau, or grow on every pass? That distinction matters before making forced GC part of the fix.
Also check the PowerShell version. From 7.1, ForEach-Object -Parallel reuses a runspace pool by default; -UseNewRunspace changes that behavior. The pool size is controlled by -ThrottleLimit. That makes the version and switches relevant to reproducing this, even if the example code is only a placeholder.
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/foreach-object?view=powershell-7.5
2
u/da_chicken Oct 13 '26
Does
[System.GC]::Collect()recover the memory? If not, then there's probably a memory leak in one of the commands you used.Get-Contentused to be known for this.1
u/iiiRaphael Oct 13 '26
I would target fewer machines at once and use separate script instances that hit, say, 100 machines at a time. The difference is, this method needs some coordination so results go into a database and each instance checks the database for targets that have no info yet and processes a batch. At the end, launch another script which sees if there's more to do and if so, launches a script for another batch.
1
u/dodexahedron Oct 13 '26
What you want is to do these things asynchronously - not parallel.
Threads are expensive and not needed for this. You have a bunch of tasks that are spending 99% of their time waiting on the network.
Fire them all off in a collection of tasks and call WaitAll() on them.
And yes - dispose any IDisposable objects in the scriptblock before it exits. Powershell is one dotnet host process and the GC behaves accordingly.
In general, do not get in the habit of calling [GC]::Collect(), unless you know exactly what is happening, exactly why it is happening, and have no ability to fix it. In all other cases, it is the wrong thing to do.
1
u/xXFl1ppyXx Oct 13 '26 edited Oct 13 '26
would it be an option to ditch foreach-object -parallel? cmdlet overhead is a real thing and at the the same time i find it to be kinda clunky to setup when i'm not firing it from the cli
then create the powershell objects via loop, and invoke / async until everything is done and dispose everything accoringly once the jobs / tasks are finished
Few Cmdlets, Not many collections / lists / arrays are getting passed around, you'd probably not even need to endinvoke / get the task results because the result bag never left it's place
edit:
of course this can be structured as a function too;
1
u/boydeee Oct 14 '26
Long lived powershell processes do tend to hold on to memory in my experience. As others mentioned, async tasks are much more lightweight.
I've done memory dumps when running a bunch of thread jobs and it's just a bunch of native powershell stuff that takes a while to get garbage collected. It typically gets cleaned up, but i tend to see a slow leak that grows over time. I did some forced garbage collections on a schedule and that helped a bit.
1
u/purplemonkeymad Oct 13 '26
It might end up being even if your example code is not. Since you are talking about memory it could be that you have a reference that is not getting cleaned up. Hard to say for real if that is the case, you would probably have to use VS to profile the ps process, but if you are using any objects in your loop that are IDisposable, make sure to try and .dispose() of them at the end of the loop.
Also looking at the commands make sure you are running the core version of powercli and not having it create a local session to Windowspowershell for each thread.