我在Powershell w.r.t中遇到了一种非常令人惊讶的抑制错误的行为。到Select命令。为了显示(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行,错误报告如下所示:
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来结束我的脚本?
发布于 2019-02-11 09:21:20
在@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
}https://stackoverflow.com/questions/54405307
复制相似问题