我们从小就听过有关 PowerShell 的两种错误类型的故事:终止错误和非终止错误。
描述非终止错误的是它只是将输出输出到错误流并允许脚本继续执行。但是,它不能被 try/catch 捕获,因为实际上没有异常被“抛出”。
至于终止错误,它将错误输出到错误流,如果未处理,则完全停止脚本的轨道,防止执行发生错误的行以下的任何内容。它可以被 try/catch 捕获。
然而,似乎还有第三种类型的错误,我似乎无法找到有关它的信息或名称。
这是一个错误,它是一种终止和非终止错误的混合......生成时,它不会终止脚本,赋予它非终止错误的属性,但它可以被一个try/catch,它赋予它终止错误的属性!
这是最基本的错误类型。它是由 .NET 本身而不是 PowerShell 的函数或 cmdlet 直接抛出的异常。
几个例子:
'a'.Split([object[]])
问题是,这些叫什么,为什么它们与其他两种类型不同?该对象仍然是一个 ErrorRecord,而不是一个 Exception,所以它们的行为应该像终止或非终止错误,而不是两者的突变。
最佳答案
Microsoft 没有专门的“它”名称,即使您需要设置 $ErrorActionPreference = "Stop"
,他们也只是将其称为终止错误。使它们的行为与终止错误相同(停止脚本)。
Because Windows PowerShell does not recognize "nonsenseString" as a cmdlet or other item, it returns a CommandNotFoundException error. This terminating error is trapped by the specific Trap statement.
The following script example contains the same Trap statements with a different error:
trap {"Other terminating error trapped" } trap [System.Management.Automation.CommandNotFoundException] {"Command error trapped"} 1/$null
Running this script produces the following result:
Other terminating error trapped Attempted to divide by zero. At C:PS> errorX.ps1:3 char:7 + 1/ <<<< $null
The attempt to divide by zero does not create a CommandNotFoundException error. Instead, that error is trapped by the other Trap statement, which traps any terminating error.
来源:about_Trap @ technet.microsoft.com
关于powershell - 隐晦的第三种错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29883990/