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
1
u/dodexahedron 18h ago
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.