I am trying to do something pretty simple with powershell and xml, but I have no problem. Basically I am trying to take the following xml ... and sort the elements of the machine by name. Then return them to XML so that I can save it back to the file.
Sorting seems to work if a new $ object is displayed, however during replacechild it complains: "It is not possible to convert the argument" 0 "with the value:" System.Object [] "to" ReplaceChild "to type" System.Xml. "XmlNode ":" Cannot convert "System.Object []" to type "System.Xml.XmlNode".
If I do a Get-Member for both $ orig and $ new, they both say they are of type XMLElement, which I assume is inherited from XMLNode.
What do I miss guys with? Drives me crazy. Thank you for your help!
<company>
<stuff>
</stuff>
<machines>
<machine>
<name>ca</name>
<b>123</b>
<c>123</c>
</machine>
<machine>
<name>ad</name>
<b>234</b>
<c>234</c>
</machine>
<machine>
<name>be</name>
<b>345</b>
<c>345</c>
</machine>
</machines>
<otherstuff>
</otherstuff>
</company>
[xml]$xml = (get-content Company.xml)
[XmlNode]$orig = $xml.Company.Machines
[XmlNode]$new = ($orig.Machine | sort Name )
$xml.Company.ReplaceChild($new, $orig)
source
share