请考虑以下代码段:
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退出,因此脚本似乎已成功。
答案 0 :(得分:4)
事实证明这是微不足道的。我不应该使用Write-Error,而只是直接输出异常:
function fail {
throw "simulated failure"
}
try {
fail
} catch {
$_
exit 1
}
,输出为:
simulated failure
At D:\tmp\Untitled2.ps1:2 char:14
+ throw <<<< "simulated failure"
+ CategoryInfo : OperationStopped: (simulated failure:String) [], RuntimeException
+ FullyQualifiedErrorId : simulated failure
更新:
这种方法显然会写入输出流。如果你想要写入错误流(正如Write-Error那样),你可能会运气不好,根据这篇文章:How do I write to standard error in PowerShell?。 Write-Error不能用于编写特定的字符串(它添加了自己的东西),并且没有相当于Write-Error的方法可以很好地处理重定向。我个人希望看到一个模拟Out-Default的Out-Error cmdlet,但会写入当前管道元素的错误流。