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 🙂

Replace text in a file using Batch script

Yesterday I was working at client site. It is a Windows server isolated from external internet access and prohibited to install any new software. I got a task in hand to remove all yaml files id to null. For example, the input file temp.yaml looks like this:

id: 4
something else
id: 64
next one
id: 231
another one
id: 34

and the target file(result.yaml) I want would be like this:

somthing else
next on
another one

It is a huge file and it would takes a long time to remove each id number one by one manually. The only tool accessible on that windows server machine is a CMD command prompt, therefore we could write a simple batch script to get the job done. Create a file called convert.bat with text editor like this:

@echo off
(for /f "tokens=1* delims=:" %%a in (temp.yaml) do (
if "%%b"=="" (echo %%a) else (
echo %%a|find " id" >null&& echo %%a: ||echo %%a: %%b

You can replace the text temp.yaml and result.yaml in the script to your target input and output file respectively. Double click to execute the script and you are done!

For those who are not familiar with Batch script, here are some basic explanation:

@echo off means to get rid of that C:Download prompt

The for loop has some option, where tokens= specify which numbered items to read from each line (default =1) and delims= specify the delimiter character (default = a space). The %%paramater are variables similar to arguments to batch files. The last line export the result to the file I want. It saves a lot of time with this simple script instead of doing manual work 🙂