我已经阅读过echo
(Write-Output
)和Write-Error
的差异,但我仍然遇到异常和堆栈跟踪问题。
以下示例演示了我的问题:
$ErrorActionPreference = "stop"
trap {
echo "Trap encountered. Exiting with 1. See errors below."
echo $_ # This is a test
Write-Error -ErrorRecord $_
exit 1
}
BROKEN_COMMAND
我不会发布输出,因为它是本地化的,但要点是:
echo
输出“BROKEN_COMMAND”未被发现是CmdLet等,并输出找到问题的完全位置的callstack,上面将是第10行左右。< / LI>
Write-Error
输出行“BROKEN_COMMAND”也未被发现是CmdLet,但随后callstack显示 Write-Error 语句所在的行而不是正确的callstack(第5行如何正确写入错误频道?我尝试省略-ErrorRecord
但没有效果。
我需要错误通道来处理错误,因此将所有内容转储到echo中,然后在错误通道中写入“出现错误”并不是一个好的选择。
更新:我使用throw
(实际为throw $_
)测试了@ MathiasR.Jessen提示。
然而,这导致程序立即退出,而$LASTEXITCODE
中没有有用的退出代码,我需要正确地发出结束信号。我的exit 1
没有被执行,并且没有正确的退出代码就会终止。
答案 0 :(得分:1)
请参阅Writing to error stream in Powershell using Write-Error
写入错误cmdlet将显示您的消息,后跟写入错误cmdlet本身的行号。
在链接的问题中,有人说这种行为在某些时候会被扼杀。
在任何一种情况下......试试这个
Get-Help About_Preference_Variables
中的hidin提到了$ErrorView
变量
NormalView(默认)
Trap encountered. Exiting with 1. See errors below.
BROKEN_COMMAND : The term 'BROKEN_COMMAND' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a
path was included, verify that the path is correct and try again.
At C:\errors.ps1:11 char:1
+ BROKEN_COMMAND
+ ~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (BROKEN_COMMAND:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
C:\errors.ps1 : The term 'BROKEN_COMMAND' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the
name, or if a path was included, verify that the path is correct and try again.
At C:\errors.ps1:6 char:6
+ Write-Error -ErrorRecord $_
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (BROKEN_COMMAND:String) [Write-Error], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException,errors.ps1
但如果你设定
$ErrorView = "CategoryView"
你得到了
Trap encountered. Exiting with 1. See errors below.
ObjectNotFound: (BROKEN_COMMAND:String) [], CommandNotFoundException
ObjectNotFound: (BROKEN_COMMAND:String) [Write-Error], CommandNotFoundException
也许这更有用
你可能想改变你的想法 echo $ _ 至 echo $ _。tostring()另见https://blogs.msdn.microsoft.com/powershell/2006/06/21/errorviewcategoryview/
遗憾的是你无法编写自己的错误表单,如log4