Tech Blog‎ > ‎

Edit XML using Powershell

posted Sep 24, 2012, 10:57 AM by Victor Zakharov   [ updated Sep 24, 2012, 11:17 AM ]
Because there is no easy/built-in way to edit XML using Powershell, I wrote a script that can change parts of XML documents.
I used it for bulk edit of connections in Remote Desktop Manager, to change some values in RDP session over dozens of servers.
You can modify it for your needs - in simple cases you would only need to change ArrayOfConnection to your document's root.

param($Path,$Key,$Value)
$doc = [xml](gc $Path)
$doc.ArrayOfConnection.ChildNodes | foreach {
  $node = $_.SelectSingleNode($Key);
  if($node -eq $null) {
  $node = $doc.CreateElement($Key);
        $node.InnerText = $Value;
  $_.AppendChild($node);
  } else {
  $node.InnerText = $Value;
  }
}
$doc.Save($Path + ".new")

Usage:

script-name C:\temp\my.xml NodeName NodeValue