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

时间:2014-10-13 02:38:53

标签: powershell

问题:powershell脚本因为使用$ ErrorActionPreference时应该被try块捕获的异常而停止

示例:

$ErrorActionPreference = 'Stop'
try {
    ThisCommandWillThrowAnException
} catch {
    Write-Error 'Caught an Exception'
}
# this line is not executed. 
Write-Output 'Continuing execution'  

1 个答案:

答案 0 :(得分:3)

解决方案:默认情况下,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'