首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么‘`exit`’会抑制Select的错误?

为什么‘`exit`’会抑制Select的错误?
EN

Stack Overflow用户
提问于 2019-01-28 15:33:51
回答 1查看 81关注 0票数 0

我在Powershell w.r.t中遇到了一种非常令人惊讶的抑制错误的行为。到Select命令。为了显示(IMHO)预期行为,我首先给出了一个使用Get-Content的最小示例。

获取内容

代码语言:javascript
复制
try {
    Get-Content -Path "NonExistingFile.txt"
}
finally {
    exit 42
}

正如预期的那样,这会引发一个错误(包括。信息):

代码语言:javascript
复制
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行,错误报告如下所示:

代码语言:javascript
复制
try {
    Select-Xml -Path "NonExistingFile.xml" -XPath "*"
}
finally {
    exit 43  # comment this out to get error message
}

有出口的行为:

代码语言:javascript
复制
PS > .\sx-nonexistingfile.ps1
PS > echo $LASTEXITCODE
43

不需要退出(为了清楚起见直接调用命令):

代码语言:javascript
复制
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来结束我的脚本?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-02-11 09:21:20

@Mathias R. Jessen's suggestion in the comment之后,我确定的最佳解决方案是脚本中的一个catch块:

  1. 引入自定义错误报告功能
  2. 在显式catch块中使用它来重新抛出任何异常。

在此基础上:

代码语言:javascript
复制
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)
}

脚本变成:

代码语言:javascript
复制
try {
    Select-Xml -Path "NonExistingFile.xml" -XPath "*"
}
catch {
    Report-Error $_
}
finally {
    exit 43
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54405307

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档