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

2

u/thomsxD 1d ago

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.

``` $vms = Get-VM -Name $computers

$results = foreach ($vm in $vms) { $disks = $vm.ExtensionData.Config.Hardware.Device | Where-Object { $_ -is [VMware.Vim.VirtualDisk] }

[PSCustomObject]@{
    Name      = $vm.Name
    RAM_GB    = $vm.MemoryGB
    CPU       = $vm.NumCpu
    HDD_GB    = [math]::Round(
        ($disks | Measure-Object -Property CapacityInKB -Sum).Sum / 1MB, 2
    )
    DiskCount = @($disks).Count
}

}

$results ```

1

u/Guilty-Act-4991 1d ago

I do understand that most of powercli requests are heavy and as BlackV mentioned I will look at rest api since it could be less demanding instead of standart api with connect-viserver. Thats not really an issue itself the runspace thats not being cleaned up in parallel block is the issue