This page looks best with JavaScript enabled

Edit XML using Powershell

 ·   ·  ☕ 1 min read

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
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:

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

Victor Zakharov
WRITTEN BY
Victor Zakharov
Web Developer (Angular/.NET)