I created a ForEach-Object which works, but as soon as I add the -Parallel flag the loop fails with "you cannot call a method on a null-valued expression". I'm using Powershell 7.2
$outputArray = [System.Collections.ArrayList]@()
$outputArrayP = [System.Collections.ArrayList]@()
$testArray =[System.Collections.ArrayList]@()
$testArrayP =[System.Collections.ArrayList]@()
for ($i=0; $i -le 1000;$i++){
$testArray.Add("Hello $i")>$null
$testArrayP.Add("Hello $i")>$null
}
$testArray | ForEach-Object {
$outputArray.Add("Hello $_")>$null
}
$testArrayP | ForEach-Object -Parallel{
$outputArrayP.Add("Hello $_")>$null
} -ThrottleLimit 5
The actual code stores database queries in an array that I want to run in parallel instead of this sample code.
Related question Making Requests in Parallel with Powershell results in "You cannot call a method on a null-valued expression" where the answer code works also in parallel, but does not answer why my code would fail.