I have adopted the use of xml files as configuration files for any PowerShell scripts I’ve been writing for work lately. Today I just found an odd bit of behavior when working with building a new xml file (if the script runs and sees no existing xml config file, it creates one). Normally, adding child objects in xml is fairly straightforward. Assume this is the existing xml.
<installcontrol>
<serverlist>
<server>
<servername>ALDARAAN</servername>
<servername>TATOOINE</servername>
</server>
</serverlist>
<installcontrol>
We can use this script to add a new child server, DANTOOINE.
$xmlFile = Get-Content $xpath
$objNewServer = $xmlFile.CreateElement(“server”)
$objNewServerName = $xmlFile.CreateElement(“servername”)
$objNewServerName.Set_InnerText(“DANTOOINE”)
$objNewServer.AppendChild($objNewServerName)
$xmlFile.installcontrol.serverlist.appendchild($objNewServer)
$xmlFile.Save(“$xpath”)
This is great, but what if there are no child objects already present, such as in this xml file.
<installcontrol>
<serverlist>
<server>
</server>
</serverlist>
<installcontrol>
Powershell complains that it can’t add append a child to a string. The script needs to change slightly to accomodate. The following snippet will work both for empty parents and also populated parents. The difference is in the 6th line.
$xmlFile = Get-Content $xpath
$objNewServer = $xmlFile.CreateElement(“server”)
$objNewServerName = $xmlFile.CreateElement(“servername”)
$objNewServerName.Set_InnerText(“DANTOOINE”)
$objNewServer.AppendChild($objNewServerName)
$xmlFile.installcontrol[“serverlist”].appendchild($objNewServer)
$xmlFile.Save(“$xpath”)
Dude! You’re awesome!
I have been all over blogs, in forums, buying books (4 of them!) and pouring over docs trying to find this answer!
I’ve been pounding my head against psbase, loosing sleep and hair the whole time!
I’ve got 4 pages of OneNotes with no answers just on this issue, and you’ve got the answer in one slightly tweaked line!
Yes!! The only thing I hate about the internet is there’s no way to buy someone a beer!
Thank you!