Foreach对象并行块内的错误处理-Powershell 7

问题描述

在Foreach-Object并行块下面捕获错误的最佳方法是什么,因为将有三个单独的线程/运行空间运行并执行写入该块中的代码,并且可能同时发生多个错误/异常?是否可以将所有错误捕获到列表/变量中并在脚本执行结束时显示

1..3 | ForEach-Object -ThrottleLimit 3 -Parallel  {
            #Some code here that throws error                
}

解决方法

-ErrorVariable参数将在末尾为您提供ErrorRecords的数组列表:

1..3 | ForEach-Object -ThrottleLimit 3 -Parallel {
    throw "Item $_ Error"
} -ErrorVariable allErrors