Add elements to XML using PowerShell

Q. How can I add elements to an XML file with PowerShell?

A. It's actually fairly easy to add content to an XML file using PowerShell. The first step is to create a new XML element containing your required data. The example below is taken from a FAQ I wrote about adding a timezone to an unattend answer file when creating a Nano server (http://windowsitpro.com/windows-server-2016/customize-nano-server-deployment-during-creation). The code below creates a TimeZone element then sets the value.

$child = $xml.CreateElement("TimeZone", $xml.unattend.NamespaceURI)
$child.InnerXml = "Central Standard Time"

The next step is to append the new XML element to the section of the XML file required. I needed to add to the component element of oobeSystem settings section which I search for that is part of the greater unattend section and add the element using:

$null = $xml.unattend.settings.Where{($_.Pass -eq 'oobeSystem')}.component.appendchild($child) 

Notice the $xml is the XML file and then the elements of the XML, .unattend then .settings and the specific settings instance I want to add to (oobeSystem).

The complete code is:

$xml = [xml](gc $UnattendFile)

$child = $xml.CreateElement("TimeZone", $xml.unattend.NamespaceURI)
$child.InnerXml = "Central Standard Time"
$null = $xml.unattend.settings.Where{($_.Pass -eq 'oobeSystem')}.component.appendchild($child) 

$xml.Save($UnattendFile)

You can use this as a basis for any additions you may require in your own files. You could also modify the value of existing elements using the same syntax, for example to set a value I could use:

$xml.unattend.settings.Where{($_.Pass -eq 'oobeSystem')}.component.<element>.Value = "<value I want>"

 

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish