0

i need to make a script for "check/replace/add string to the file. The "correct" string is "google.com 44.10.15.9" I have a part of the script for adding the whole line, but i don't know how to make it check other options, If the string would be there but only "google.com" without address or with wrong address. My work looks like this.

$file= 'C:\Users\fialbvoj\Desktop\testPS.txt'
$name=" google.com "
$IP=" 44.10.15.9 "
$line="google.com 44.10.15.9"
$search=(Get-Content $file | Select-String -Pattern 'google.com 44.10.15.9').Matches.Success

if ($search ) {"Success"
} else {
    Add-Content -Path $file -Value $line
}

Thank you in advance. Best Regards

slouly
  • 11
  • 3
  • If you’re editing the Windows “hosts” file, there’s a load of examples in this question that you might be able to build something from… https://stackoverflow.com/questions/2602460/powershell-to-manipulate-host-file – mclayton Sep 06 '22 at 08:08

1 Answers1

2

Select-String accepts regular expressions for the -Pattern parameter which allows you to use a regular expression for the IPAddress instead of a literal IP address, e.g.:

 ... |Select-String 'google\.com ((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}'

To replace the any pattern with the "correct string" (aka IP address):

(Get-Content $file) -Replace 'google\.com ((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}', 'google.com 44.10.15.9' |Set-Content $file

Note 1: the parenthesis around (Get-Content $file) are only required if you need to write back to the same file.
Note 2: the backslash in google\.com is required to escape the dot which normally represents any character in a regular expression.

iRon
  • 20,463
  • 10
  • 53
  • 79