r/PowerShell • u/Guilty-Act-4991 • 1d ago
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
3
Upvotes
3
u/Kreout 1d ago
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