NebulousNifty
NebulousNifty

Reputation: 35

Find a file, find a line in a file and change that line

I need to find files on a server that contain a specific line of text, I then need to replace that line of text with a new one.

surfed the internet and tried several methods to write to the file.

$path = "C:\users\
$filename = "myfile.ini"

$searchString="Program=C:\Program Files (x86)\Over\Here"
$newString="Program=C:\Program Files (x86)\Here

Get-ChildItem -Path $Path -Recurse -Filter $filename -ErrorAction SilentlyContinue | foreach-object {

(Get-Content $_.FullName) | ForEach-Object {$_ -replace [regex]::Escape($searchString), [regex]::Escape($newString) } | Set-Content $_.FullName

}

I'm expecting my file to look like this.

Program=C:\Program Files (x86)\Here

But I get this.

Program=C:\\\Program\ Files\ (x86\\)\\\Here

I suspect it has to do with the "\" in the file path, but I can't figure out out to get them to behave correctly.

Upvotes: 0

Views: 39

Answers (1)

js2010
js2010

Reputation: 27606

Don't escape the second argument.

 -replace [regex]::Escape($searchString), $newString 

Upvotes: 1

Related Questions