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

时间:2017-02-16 06:30:32

标签: powershell suppress

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

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

1 个答案:

答案 0 :(得分:0)

在命令周围放置一个try catch

public class BinaryTree {
Node root;

public BinaryTree() {
    root = null;
}    

void deleteTree(Node node){
    if(node==null)
        return;
    deleteTree(node.left);
    deleteTree(node.right);
    System.out.println("The deleted node is " + node.key);
    node = null;
}

void deleteTreeRef()
{
    deleteTree(root);
    root=null;
}
}