【问题标题】:Powershell script stops on exception caught in try/catch block; $ErrorActionPreferencePowershell 脚本在 try/catch 块中捕获到异常时停止; $ErrorActionPreference
【发布时间】:2014-12-07 13:21:00
【问题描述】:

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

例子:

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

【问题讨论】:

    标签: powershell


    【解决方案1】:

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    相关资源
    最近更新 更多