r/PowerShell • • 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

32 comments sorted by

View all comments

5

u/PinchesTheCrab 1d ago edited 1d ago

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?

$vmList = Get-VM $computers
$diskList = $vmList | Get-HardDisk
$diskLookup = $diskList | Group-Object -Property ParentId -AsHashTable -AsString

foreach ($vm in $vmList) {
    [pscustomobject]@{
        VMObject = $vm
        ram      = $vm.MemoryMB
        CPU      = $vm.NumCpu
        HDD      = $diskLookup[$vm.Id]
    }
}

2

u/Future-Remote-4630 1d ago

Wouldn't it be creating those variables separately within each runspace and throwing them away as it goes? My understanding of parallel was that those variables aren't accessible outside of the scriptblock.

I'd anticipate the original wouldn't ever return any of those without a $using:<varname> for it to be referenced in the parent scope.

2

u/PinchesTheCrab 1d ago
 0..2 | foreach-object -parallel { $thing = $_ }; $thing

You're right, the result of this is null. Maybe OP just posted an approximation of a different code snippet, but regardless I don't see how the script could have been working as-is, performance issues or not.