Powershell 脚本在 try/catch 块中捕获异常时停止;$ErrorActionPreference

Vla*_*rov 5 powershell

问题: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)

Vla*_*rov 7

解决方案: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)