Variable returns empty when using foreach-object -parallel

75 Views Asked by At

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.

1

There are 1 best solutions below

0
Paul Jebastin On

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

thread 1: $sum (0) + $numbers[0] (1) = 1
thread 2: $sum (0) + $numbers[1] (2) = 2
thread 3: $sum (0) + $numbers[2] (3) = 3
thread 4: $sum (0) + $numbers[3] (4) = 4
thread 5: $sum (0) + $numbers[4] (5) = 5

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:

1.. 100 | ForEach-Object -begin {$sum=0 }-process {$sum+=$_} -end {"The total of the numbers input is $sum"}

$(for($i=0;$i -le 100; $i+=5){$i} ) | ForEach-Object -begin {$sum=0 }-process {$sum+=$_} -end {"The sum by fives of the numbers input is $sum"}

Thank you