我在Powershell w.r.t中遇到了(对我来说)非常令人惊讶的错误抑制行为。到Select-Xml Commandlet。为了显示(IMHO)的预期行为,我首先显示一个带有Get-Content
的最小示例:
获取内容
try {
Get-Content -Path "NonExistingFile.txt"
}
finally {
exit 42
}
如预期的那样,这将引发错误(包括消息):
PS > .\gc-nonexistingfile.ps1
Get-Content : Der Pfad "NonExistingFile.txt" kann nicht gefunden werden, da er nicht
vorhanden ist.
In gc-nonexistingfile.ps1:2 Zeichen:5
+ Get-Content -Path "NonExistingFile.txt"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (...xistingFile.txt:String) [Get-Content],
ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand
PS > echo $LASTEXITCODE
42
选择Xml
如果我对
Select-Xml
做同样的事情,则错误消息会被吞噬,但是只有当我使用exit
关键字时,错误信息才会被吞并。如果我删除了exit
行,则会报告上述错误:try {
Select-Xml -Path "NonExistingFile.xml" -XPath "*"
}
finally {
exit 43 # comment this out to get error message
}
退出行为:
PS > .\sx-nonexistingfile.ps1
PS > echo $LASTEXITCODE
43
不退出(为清楚起见直接调用命令行开关):
PS > Select-Xml -Path "NonExistingFile.xml" -XPath "*"
Select-Xml : Der Pfad "NonExistingFile.xml" kann nicht gefunden werden, da er nicht
vorhanden ist.
In Zeile:1 Zeichen:1
+ Select-Xml -Path "NonExistingFile.xml" -XPath "*"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (...xistingFile.xml:String) [Select-Xml],
ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.SelectXmlCommand
题
我的问题:为什么有区别?并且:尽管我使用
Select-Xml
结束了我的脚本,但如何才能使exit
明显抛出其错误?
最佳答案
在@Mathias R. Jessen's suggestion in the comment之后,我确定的最佳解决方案是脚本中的catch
块:
接着就,随即:
function Report-Error ($Error)
{
$FormatString = "{0} : {1}`n{2}`n" +
" + CategoryInfo : {3}`n" +
" + FullyQualifiedErrorId : {4}`n"
$ErrorFields = $Error.InvocationInfo.MyCommand.Name,
$Error.ErrorDetails.Message,
$Error.InvocationInfo.PositionMessage,
$Error.CategoryInfo.ToString(),
$Error.FullyQualifiedErrorId
Write-Host -Foreground Red -Background Black ($FormatString -f $ErrorFields)
}
脚本变为:
try {
Select-Xml -Path "NonExistingFile.xml" -XPath "*"
}
catch {
Report-Error $_
}
finally {
exit 43
}
关于powershell - 为什么 `exit`抑制Select-Xml的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54405307/