Home/PowerShell/How to write data to an xml file using Powershell

How to write data to an xml file using Powershell

Recently, I came up with a requirement of updating an config file (Xml data) in our PROD environment without login in to the sever to avoid the manual error, which lead to create this post. Let we start this implementation by step by step, here I’m using the XmlDocument .Net object here but it is possible to utilize other .Net classes, e.g. XPath and/or XDocument.

Sample XML file (web.config) 

This is the sample Web.config file which is going to be use for this whole post. 

STEP: #1 Creating XML Elements

Here my goal is to add the “Powershell” tutorial topic at end of all other topic (ie., after OOPS) in the above xml file (extension is .config file). First we need to load the XML document (physical location of web.config) as like below,

[xml]$XmlDocument = Get-Content -Path $FilePath

STEP: #2 Searching the XML Element in the XmlDocument:

Next we need to search for the element for updating our value in the .config file. Based on the input parameter $Selector, it applies the specified pattern-matching operation to this node’s context and returns the first matching node. If no nodes match the expression, the method returns a null value.

#$Selector : //tutorials[@name=’tutorial:start’]
$events = $XmlDocument.SelectSingleNode($Selector)
$topic = $events.Topics

After execution of the first line of code, the $events variable will hold the below elements (filtered based on the input value $Selector). In the next execution it filter with Topics and sassing to the @sites variable.

STEP: #3 Creating New XML Elements

Now we can create our new element/node (ie., <Topic>Powershell</Topic>) and append it to the parent reference. Then you an append the value for the New Element with help of InnerText.

$child = $XmlDocument.CreateElement(“Topic”)
$child.InnerText = $NewTutorialTopic

STEP: #4 Adding Nested XML Elements

Finally we need to add elements by appending and save to the loaded XML file

$topic.AppendChild($child)
$XmlDocument.Save($FilePath)

Final Code

OUTPUT 

Leave a Reply