Replace text in xml files with Powershell

Powershell Script

Yesterday I was working at client site. It is a Windows server isolated from 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 takes 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:UsersvictorleungtwDesktopTest -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 🙂

By Victor Leung

Experience in software development, consulting services and technical product management. Understanding of business and technology with an MBA in Finance and a Master degree in Computer Science. AWS Certified Solution Architect with experience in building products from scratch and serving as a charismatic leader.

Leave a comment

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.