Replace Text in XML Files with PowerShell

July 31, 2018

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.

b973d 1tzyukn6zafokohheoobm3w 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:

      <Report Name="My Report">

The expected output file, temp-new.xml, should have a structure like this:

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

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);

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! 😃

Profile picture

Software development professional with expertise in application architecture, cloud solutions deployment, and financial products development. Possess a Master's degree in Computer Science and an MBA in Finance. Highly skilled in AWS (Certified Solutions Architect, Developer and SysOps Administrator), GCP (Professional Cloud Architect), Microsoft Azure, Kubernetes(CKA, CKAD, CKS, KCNA), and Scrum(PSM, PSPO) methodologies. Happy to connect