Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error handling within Foreach-object Parallel block - Powershell 7

What would be the best way to capture error within below Foreach-Object Parallel block as there would be three separate threads/runspaces running and executing code written in the block and multiple errors/exception can occurs at the same time? Would it be possible to capture all the errors in a list/variable and show at the end of the execution of the script?

1..3 | ForEach-Object -ThrottleLimit 3 -Parallel  {
            #Some code here that throws error                
}
like image 608
nrawal Avatar asked Dec 31 '25 08:12

nrawal


1 Answers

The -ErrorVariable param will give you an arraylist of ErrorRecords at the end:

1..3 | ForEach-Object -ThrottleLimit 3 -Parallel {
    throw "Item $_ Error"
} -ErrorVariable allErrors
like image 98
Brian Reynolds Avatar answered Jan 03 '26 15:01

Brian Reynolds



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!