Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String replacement in a file using PowerShell

Tags:

powershell

I'm trying replace a few strings within another PowerShell file.

$Source_IP = Read-Host 'Enter source IP'
$Target_IP = Read-Host 'Enter target IP'

By using the following line in another PowerShell script, the file shows as Modified, but the changes don't take effect.

(Get-Content "C:\Solutions.ps1") -replace "$Target_IP = Read-Host 'Enter target IP'", "$Target_IP = '192.168.0.221'" | Set-Content "C:\Solutions.ps1"

Is there a reason why the changes don't take effect?

This is running as an Administrator, on Windows Server 2008, and PowerShell version 2 I believe.

like image 427
Elarys Avatar asked Jan 28 '16 13:01

Elarys


People also ask

How do I replace a character in a PowerShell file?

Use Get-Content and Set-Content to Replace Every Occurrence of a String in a File With PowerShell. The Get-Content gets the item's content in the specified path, such as the text in a file. The Set-Content is a string-processing cmdlet that allows you to write new content or replace the existing content in a file.

How do you replace a line in a file using PowerShell?

To replace a line in a file, use PowerShell replace() method that takes two arguments; string to find and string to replace with found text. After the replacement of a line in a file, pipe the output to the Set-Content cmdlet to save the file.

How do I replace multiple characters in a string in PowerShell?

You can replace multiple characters in a string using PowerShell replace() method or PowerShell replace operator. If you are using the PowerShell replace() method, you can chain replace() method as many times to replace the multiple characters in the PowerShell string.

How do I update a text file in PowerShell?

The easiest way to edit a text file in PowerShell on your Windows machine is to run the command notepad.exe my_text_file. txt , or simply notepad my_text_file. txt , in your PowerShell terminal to open the text file with the visual editor Notepad.


1 Answers

As PetSerAl points out the -replace comparison operator supports regex. While you can have some degree of expressions in your patterns you are adding an unnecessary amount of complexity especially since you are just using simple matches anyway.

The easier solution is to use the string method .Replace().

$filePath = "C:\Solutions.ps1"
(Get-Content $filePath).Replace($Source_IP,$Target_IP) | Set-Content $filePath

Note that .Replace() is case sensitive. If you are just replacing IP addresses it is a moot point. I am unsure why you are having issues with a second file.

like image 177
Matt Avatar answered Sep 26 '22 20:09

Matt