Replace text in XML files with Powershell

Victor Leung
Jul 31, 2018 · 2 min read
Powershell Script

Yesterday I was working at a client site. It is a Windows server isolated from the external network. It is not allowed to install any third-party software in the machine. However, I got a task in hand to replace all XML files name from “My Report” to “My Report (New)”. The original file temp.xml looks like this:

<Report Name="My Report">

while the excepted output temp-new.xml file I want for import looks in a structure like this:

<Report Name="My Report (New)">

I have no tools in hand and it would take many hours to replace hundreds of files one by one manually. The only thing accessible for scripting is the PowerShell. Here are a few lines of code to get things done.

Step 1: Load all XML files inside my Test folder.

$files = Get-Childitem C:\Users\victorleungtw\Desktop\Test -Recurse -Include *.xml

Step 2: Modify all report name and add “ (New)” after the original name

$xmldata = [xml](Get-Content $file); 
$name = $xmldata.ReportList.Report.GetAttribute("Name");
$name = $name + " (New)"; $xmldata.ReportList.Report.SetAttribute("Name", $name);

Step 3: Change the file name from temp.xml to temp-new.xml

Get-ChildItem *.xml | Rename-Item -NewName { $ -Replace '\.xml$','-new.xml' }

Done! All the files are changed. Happy coding :)

Victor Leung

Written by

I’m a keen traveler to see every country in the world, passionate about cutting edge technologies.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade