gpt4 book ai didi

powershell - 如何显示使用 Write-Error 引发异常的位置?

转载 作者:行者123 更新时间:2023-12-02 23:15:42 25 4
gpt4 key购买 nike

考虑以下代码段:

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 退出,因此脚本似乎已经成功。

最佳答案

事实证明这是微不足道的。我不应该使用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。

关于powershell - 如何显示使用 Write-Error 引发异常的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10518859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com