gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 23:28:24 25 4
gpt4 key购买 nike

问题:powershell 脚本由于使用 $ErrorActionPreference 时应由 try 块捕获的异常而停止

例子:

$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'

关于Powershell 脚本在 try/catch block 中捕获的异常时停止; $ErrorActionPreference,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26332167/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com