Unwanted Output

When using certain .net libraries, I get unwanted console output from the code, almost like a developer left some ‘printf’ debugging statements in there unintentionally. For instance, the following function looks for a child node in an XML document and adds it with a default value if it is not found. When I use it in a script, the default value is always printed to the console. I’ve run it in the debugger, but due (i suppose) to when the console is flushed I can’t even pin down exact line that is causing it. But it’s definitely happening in the .net library code, as I have no echo or write statements anywhere in my script.

Is there a way to suppress this somehow? Its quite annoying.

# Checks for one given element, adding it with a default value if it is missing
function setIfMissing(
    # The parent container
    [System.Xml.XmlElement]$parentNode, 
    # The specific element we are checking for (ns qualified)
    [string]$nodeName, 
    # The default value to assign if it is not found.
    [string]$defaultValue, 
    # A namespace manager to use
    [System.Xml.XmlNamespaceManager]$nsmgr) 
{
    # find the current value
    $currentValue = $parentNode.SelectSingleNode($nodeName, $nsmgr)

    #check if it is null
    if (!$currentValue) {

        # create a new node
        $ownerDoc = $parentNode.OwnerDocument
        $newNode = $ownerDoc.CreateElement($nodeName, $namespace)
        # Set its value. If the default value is null, create the node anyhow,
        # But set the xsl:nil attribute
        if($defaultValue) {
            $newNode.InnerText=$defaultValue
        }
        else {
            $newNode.SetAttribute("nil", $xsiNs, "true")
        }

        # Now add it to the document.
        $parentNode.AppendChild($newNode)
    }
}

OK, so maybe this is just my lack of understanding. Looks like maybe its just printing the return value of my function and I need to suppress that behavior somehow.

The behavior you are experiencing is likely do to the “AppendChild” method. It’s return value is the Node added (https://msdn.microsoft.com/en-us/library/system.xml.xmlnode.appendchild(v=vs.110).aspx). Since you are not capturing that in a variable or outputting to null, it is output to the console.

Try changing

        # Now add it to the document.
        $parentNode.AppendChild($newNode)

to

        # Now add it to the document.
        $parentNode.AppendChild($newNode) | Out-Null

Thanks, that was it. I don’t do much powershell and am still wrapping my head around the way function return values and output actually work.

~Bill