1
有什麼辦法可以抑制這個錯誤。相反,這種醜陋的和長期的錯誤,我想捕捉返回代碼值($?),以決定成敗如何在變量賦值期間抑制PowerShell錯誤消息
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:\>
感謝您的答覆。有效。 –