繁体   English   中英

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

[英]Powershell script stops on exception caught in try/catch block; $ErrorActionPreference

问题:由于使用$ ErrorActionPreference时,try块应捕获异常,因此powershell脚本停止运行

例:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM