-3

Im trying to replace an ever-changing IP address in a text file. Here is the code I'm using.

$ConfigFile = "C:\Temp2\ConfigFile.overrides"

$content = [System.IO.File]::ReadAllText($ConfigFile).Replace("10.0.0.333","127.0.0.1")
[System.IO.File]::WriteAllText($ConfigFile, $content) 

How do I make the 10.0.0.333 into a wildcard so it would work with any IP and change it back to the loopback address.

  • 3
    If your XML file is a proper XML file you should treat it as such and access the node you want to change. That will be less error prone than using simple string replacement. – Olaf Apr 02 '21 at 18:26
  • Its not an .XML file. It's a .overrides file. Just assume it's a text file and a string replacement is sufficient. – DoesNotCompute Apr 02 '21 at 18:57
  • 1
    But 10.0.0.333 is not a valid IP address :/ – Santiago Squarzon Apr 02 '21 at 19:08
  • If you're sure it's the only IPv4 address in this file I would recommend to use standard PowerShell cmdlets instead of dotNet commands. Use `Get-Content` with a `-replace` and the regex pattern `"\d+\.\d+\.\d+\.\d+"` and save the result with `Set-Content` – Olaf Apr 02 '21 at 19:10
  • Thank you Zett42, this did it. – DoesNotCompute Apr 02 '21 at 19:37

1 Answers1

0

If you're looking for valid IP addresses in the file, this will work:

$re='\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b'
$configFile='~/Documents/test/configFile.txt'

$configFileUpdate=(Get-Content $configFile) -replace $re,'127.0.0.1'
$configFileUpdate > $configFile

PS /~> cat ./configFile.txt

test test test test test test test 
test test test test test test test 
test test 10.10.0.123 test test test
test test test test test test test 
test test test test test test test 

PS /~> ./script.ps1           

test test test test test test test 
test test test test test test test 
test test 127.0.0.1 test test test
test test test test test test test 
test test test test test test test 

This regex will not work with ỳour example 10.0.0.333 because it is not a valid IP address, for this something like the regex in Olaf's comment will work.

Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37