Replace Text in XML Files with PowerShell
Yesterday, I was working at a client site that has a Windows server isolated from the external network. Installing any third-party software on the machine is not permitted.
PowerShell Script
However, I was tasked with replacing all XML file names from “My Report” to “My Report (New)”. The original file, temp.xml, looks like this:
<ReportList>
<Report Name="My Report">
</Report>
</ReportList>
The expected output file, temp-new.xml, should have a structure like this:
<ReportList>
<Report Name="My Report (New)">
</Report>
</ReportList>
Without access to any specialized tools and facing the prospect of manually editing hundreds of files, I turned to PowerShell for scripting. Here are a few lines of code that accomplish the task:
Step 1: Load all XML files from my Test folder
$files = Get-ChildItem C:\Users\victorleung\tw\Desktop\Test -Recurse -Include *.xml
Step 2: Modify all report names by adding “ (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);
$xmldata.Save($file)
Step 3: Change the file name from temp.xml to temp-new.xml
Get-ChildItem *.xml | Rename-Item -NewName { $_.Name -Replace '.xml$','-new.xml' }
That’s it! All the files have been changed. Happy coding! 😃