I want to calculate something in a foreach-object -parallel loop and return a variable, but it keeps returning empty!
For example, I have this simple script and would like to read $sum at the end.
$numbers = @(1, 2, 3, 4, 5)
$sum = 0
$numbers | foreach-object -parallel {
$sum += $_
}
Write-Host $sum
When it leaves the loop $sum is empty How can I keep the value? Some is talking about $using: but I cannot get that to work either.
The script block with -Parallel switch which run the script block parallelly on separate process threads, so when its in the loop the sum of array will be calculated like below
Then returns the $sum variable value which assigned out of the script block. I don't think you can calculate the value and return out of the script block when using parallel switch, but if you find a way, please do update here. Here are some examples without parallel switch:
Thank you