Reputation: 669
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.
Upvotes: 7
Views: 29464
Reputation: 46730
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.
Upvotes: 9
Reputation: 94
Just to point out that, as for what stated before, the -replace operator supports regex and in a regex you have to escape special characters like $ in the search string with a \ , moreover you are using double quotes strings so you have to escape before the $ with powershell escape character ` in both search and replace strings, so the command should be (can't try it right now):
(Get-Content "C:\Solutions.ps1") -replace "\`$Target_IP = Read-Host 'Enter target IP'", "`$Target_IP = '192.168.0.221'" | Set-Content "C:\Solutions.ps1"
Upvotes: 0