How to set a counter within ForEach-Object Parallel - PowerShell 7

848 views Asked by At

I have a int variable defined outside the foreach block, trying to set it within the block and access it outside. However, when I run this script, I get below error. It seems to be a basic thing but I am new to PowerShell.

Error : The '++' operator works only on variables or on properties.

Script :

[int]$ErrorCount = 0
1..3 | ForEach-Object -ThrottleLimit 40 -Parallel  {
            $using:ErrorCount++
}

$FinishMessage = "Errors: {0}" -f $ErrorCount
echo $FinishMessage
1

There are 1 answers

0
js2010 On

A more typical idiom would be to return some properties:

1..40 | ForEach-Object -ThrottleLimit 40 -Parallel {
  sleep 1
  [pscustomobject]@{Error = $true }
} | measure error

Count             : 40
Average           :
Sum               :
Maximum           :
Minimum           :
StandardDeviation :
Property          : Error