Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell passing XMLDocument through function calls

Tags:

powershell

I'm trying to pass a System.XML.XMLDocument object through function calls, however that object is changed to System.Object[] after function call.

More specifically, I have a function like this:

function GenerateXml()
{

    [System.XML.XMLDocument]$xmlDoc=New-Object System.XML.XMLDocument
    $declaration = $xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "yes")
    $xmlDoc.AppendChild($declaration)

    [System.XML.XMLElement]$root = $xmlDoc.CreateElement("dummy")
    $root.SetAttribute("Name", "dummy value")
    $xmlDoc.AppendChild($root)
    $xmlDoc
}

[System.XML.XMLDocument]$xmlDoc = GenerateXml

This will output an error like:

Cannot convert value "System.Object[]" to type "System.Xml.XmlDocument".

So what is the best way of passing a XMLDocument through function calls?

like image 294
Jun Pang Avatar asked Mar 31 '26 16:03

Jun Pang


1 Answers

Turns out Powershell will return all the output from a method to an array. To get the actual return value, you can either get the last member of the output array or just don't output anything else other than what you actually want.

like image 175
Jun Pang Avatar answered Apr 02 '26 10:04

Jun Pang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!