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
View all comments
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;