powershellsuppress

How to suppress PowerShell error message during variable assignment


Is there any way I can suppress this error. Instead of this ugly and long error, I would like to capture return code value($?) to determine success or failure

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

Solution

  • Place a try catch around the command

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