考虑以下代码段:
function fail {
throw "simulated failure"
}
fail
运行脚本时,默认异常处理会打印引发异常的行和命令:
simulated failure
At D:\tmp\Untitled1.ps1:2 char:10
+ throw <<<< "simulated failure"
+ CategoryInfo : OperationStopped: (simulated failure:String) [], RuntimeException
+ FullyQualifiedErrorId : simulated failure
另一方面,如果我捕捉到异常并自己打印:
function fail {
throw "simulated failure"
}
try {
fail
} catch {
Write-Error $_
exit 1
}
Write-Error 的输出只告诉我错误发生在脚本内部:
D:\tmp\Untitled2.ps1 : simulated failure
At line:1 char:16
+ .\Untitled2.ps1 <<<<
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Untitled2.ps1
如何获得与第一种情况相同的输出?
注意:我想捕获异常的原因是执行“退出 1”。默认情况下,即使出现异常,powershell 也会以 0 退出,因此脚本似乎已经成功。