【问题标题】:How to suppress PowerShell error message during variable assignment如何在变量分配期间抑制 PowerShell 错误消息
【发布时间】:2017-07-05 03:01:36
【问题描述】:

有什么办法可以抑制这个错误。而不是这个丑陋而冗长的错误,我想捕获返回码值($?)来确定成功或失败

    PS C:\> $str ="<p> Hi </p>"
    PS C:\> $data = [xml]$str
    PS C:\> $?
    True
    PS C:\>
    PS C:\> $str ="<p> Hi <p>"
    PS C:\> $data = [xml] $str
    Cannot convert value "<p> Hi <p>" to type "System.Xml.XmlDocument". Error: "Unexpected end of file has occurred. The following elements are
    not closed: p, p. Line 1, position 11."
    At line:1 char:1
    + $data = [xml] $str
    + ~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
        + FullyQualifiedErrorId : InvalidCastToXmlDocument

    PS C:\> $data = [xml] $str 2> $null
    Cannot convert value "<p> Hi <p>" to type "System.Xml.XmlDocument". Error: "Unexpected end of file has occurred. The following elements are
    not closed: p, p. Line 1, position 11."
    At line:1 char:1
    + $data = [xml] $str 2> $null
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
        + FullyQualifiedErrorId : InvalidCastToXmlDocument

    PS C:\>
    PS C:\> $?
    False
    PS C:\>

【问题讨论】:

    标签: powershell suppress


    【解决方案1】:

    在命令周围放置一个 try catch

    try {$data = [xml] $str } catch {}
    

    【讨论】:

    • 太棒了!!很难找到如何处理糟糕的 powershell 输出。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-26
    • 2018-05-25
    • 1970-01-01
    • 2011-02-11
    • 2013-03-18
    • 2015-11-29
    相关资源
    最近更新 更多