Thursday, May 24, 2012

PowerShell: Copy an XML object

This is going to sound incredibly simple and stupid to some but I had a problem when I started working with XML ([xml]) objects in PowerShell regarding the creation of duplicates and/or copying of XML objects.

My scenario was that I was reading in an XML config file for Microsoft NAP, altering some values for different sites/domains, and then outputting a modified version of the XML that was specific for each site/domain that could then be imported to keep the configs identical between each site/domain.  My problem is that I was taking my local NAP server and using those values as the expected values so I didn't want it to change with each iteration of the domain/site so I thought to create a "temp" copy after reading the XML file in:

$xml = gc .\myxmlfile.xml

$sites | ForEach-Object {

   $xml2 = $xml

   ...

}


...For normal PowerShell objects, this would work fine to create a duplicate object and assign it to $xml2.  For some reason that is beyond me, this doesn't work for XML objects.  What it does is create a reference to the original object.  So if you modify the XML in $xml2 using the assignment method above, you will actually be modifying $xml. 

What I ended up discovering is that if you do a Get-Member on an [xml] object, you'll see a method called Clone().  The proper assignment in my loop that resolved this issue was:

$xml2 = $xml.Clone()

No comments:

Post a Comment