Victor Leung
Victor Leung
BlogAI SolutionAlphaAlgoFlower shopFX CombineIEESushi ClassifierWealth Agile

Replace text in xml files with Powershell

July 31, 2018

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.

b973d 1tzyukn6zafokohheoobm3w Powershell Script

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:

    <ReportList>
      <Report Name="My Report">
      </Report>
    </ReportList>

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

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

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);
     $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' }

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


About Victor Leung

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
LinkedIn
Github
Twitter
@victorleungtw

Continuous improvement

Copyright © victorleungtw.com 2023.