Find and replace strings in a file using Powershell

I had a number of files which I was required to find and replace a number of strings that matched a pattern and then save the output to a new file.

Using the Get-Content I was able to get the content of a file and output this to a variable. For the initial example I will demonstrate using a single file named D:\Folder\OldFile.txt.

Using the content from the above file now stored in a variable I am now able to search through the file to find strings that match a pattern, replace these and then save to a new file. In this example, I will be searching for the strings ‘Blue’ and ‘Green’ and replace these with ‘Red’ and ‘Yellow’ and save to the file D:\Folder\NewFile.txt.

Content = Get-Content -Path (“D:\Folder\OldFile.txt)
$Content | foreach {$_ -replace “Blue”, “Red”} | Set-Content (“D:\Folder\NewFile.txt”)
Content = Get-Content -Path (“D:\Folder\OldFile.txt)
$Content | foreach {$_ -replace “Green”, “Yellow”} | Set-Content (“D:\Folder\NewFile.txt”)

Now my objective for compiling the script was to rename multiple files in a folder by calling the For-Each object  cmdlet to perform the above example on a number of input objects, in this case multiple text files in a folder.

$Files = Get-ChildItem “D:\Folder\*.txt”
Foreach ($File in $Files)
         $Content = Get-Content -Path (“D:\Folder\” + $File)
         $Content | foreach {$_ -replace “Blue”, “Red”} | Set-Content (“D:\Folder\New_” + $File)
         $Content = Get-Content -Path (“D:\Folder\” + $File)
         $Content | foreach {$_ -replace “Green”, “Yellow”} | Set-Content (“D:\Folder\New_” + $File)



Leave a Reply

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

You are commenting using your 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 )

Google+ photo

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

Connecting to %s