问题:powershell脚本因为使用$ ErrorActionPreference时应该被try块捕获的异常而停止
示例:
$ErrorActionPreference = 'Stop'
try {
ThisCommandWillThrowAnException
} catch {
Write-Error 'Caught an Exception'
}
# this line is not executed.
Write-Output 'Continuing execution'
答案 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'