问题:powershell 脚本因使用 $ErrorActionPreference 时应该由 try 块捕获的异常而停止
例子:
$ErrorActionPreference = 'Stop'
try {
ThisCommandWillThrowAnException
} catch {
Write-Error 'Caught an Exception'
}
# this line is not executed.
Write-Output 'Continuing execution'
Run Code Online (Sandbox Code Playgroud)
解决方案:Write-Error实际上默认抛出一个非终止异常。当$ErrorActionPreference = 'Stop'设置时,Write-Error在 catch 块中抛出终止异常。
使用覆盖此-ErrorAction 'Continue'
$ErrorActionPreference = 'Stop'
try {
ThisCommandWillThrowAnException
} catch {
Write-Error 'Caught an Exception' -ErrorAction 'Continue'
}
# this line is now executed as expected
Write-Output 'Continuing execution'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3948 次 |
| 最近记录: |