首页 > 解决方案 > Powershell:如果在“try”块内引发非终止错误,则变为终止错误

问题描述

我需要一些指针来理解这种行为:

'---------------------------------'
$ErrorActionPreference = 'Continue'

function Do-Something {
    Invoke-WebRequest 'http://www.notexistanthost.xyz/notexistantpath/'
    'first error is non-terminating'

    try
    {
        Invoke-WebRequest 'http://www.notexistanthost.xyz/notexistantpath/'
        'never reached'
    }
    catch
    {
        'second time the same error becomes terminating and go in catch block'
    }

}

Do-Something

通常返回非终止错误的函数,具有相同的参数返回在try块内时会产生终止错误。

为什么以及何时发生这种情况?这与每个功能有关吗?

标签: powershell-5.0

解决方案


如果它在 try/catch 中工作,则它是一个终止错误。它鲜为人知,但有两种终止错误,脚本终止和命令终止。try 看到命令终止错误并对其进行操作。'1/0' 也是命令终止。

try { 1/0; 'hi' } catch { 'caught' } 

caught

“找不到路径”不是终止错误:

try { dir foo } catch { 'caught' } 

Get-ChildItem: Cannot find path '/Users/js/foo' because it does not exist.

推荐阅读