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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With