How to save output from Foreach parallel loop in PowerShell?
In PowerShell 7, saving the output of the foreach parallel loop requires some tricks. It is unlike a simple foreach loop. For example, in a simple foreach loop, we can directly store output to a variable that is declared outside as shown below.
$output = @()
foreach ($service in (Get-Service | where{$_.StartType -eq 'Disabled'})){
$output += [PSCustomObject]@{
'Name' = $service.name
'StartType' = $service.StartType
'Status' = $service.Status
}
}
$output
Let’s try the same with PowerShell 7.
$output = @()
Get-Service | where{$_.StartType -eq 'Disabled'} | foreach-object -Parallel {
$out= $using:output
$service = $_
$out+= [PSCustomObject]@{
'Name' = $service.name
'StartType' = $service.StartType
'Status' = $service.Status
}
}
$output
There will be no output because $out variable scope outside the foreach parallel loop is unknown. Instead, we can directly store the value to the variable outside the foreach parallel loop.
$output = @()
$output += Get-Service | where{$_.StartType -eq 'Disabled'} | foreach-object -Parallel {
$service = $_
[PSCustomObject]@{
'Name' = $service.name
'StartType' = $service.StartType
'Status' = $service.Status
}
}
$output
The output will be the same as the previous output.