如何在变量赋值期间抑制 PowerShell 错误消息

How to suppress PowerShell error message during variable assignment

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

    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:\>

在命令周围放置一个 try catch

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