tkobus
tkobus

Reputation: 33

How to replace path in text file with Powershell

I have a problem with replace text in Powershell. For e.g.

When I use:

(Get-Content C:\TEMP\App.config) -replace "one","two" | Set-Content C:\TEMP\App.config

it works. But when I use:

(Get-Content C:\TEMP\App.config) -replace "C:\Program Files (x86)\Adobe\Acrobat Reader 10\Reader\AcroRd32.exe","C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe" | Set-Content C:\TEMP\App.config

is doesn't work. I search a lot of info in Google or documentation but still have a problem.

Can anybody help? :-)

Upvotes: 3

Views: 2294

Answers (2)

Martin Brandl
Martin Brandl

Reputation: 59001

You should be aware that the -replace command uses regex. It should work, if you escape the replace string:

$searchString = [Regex]::Escape('C:\Program Files (x86)\Adobe\Acrobat Reader 10\Reader\AcroRd32.exe')
$replaceString = 'C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe'

(Get-Content C:\TEMP\App.config) -replace $searchString, $replaceString | Set-Content C:\TEMP\App.config

Upvotes: 1

Theo
Theo

Reputation: 61208

The -replace operator uses regex on the search string and replaces that with another string.
That replacement string is a normal, unescaped string.

Since your path has characters in it that have special meaning in regex, like the backslash, you need to escape the search string by prepending a backslash in front of every such special character.

Regex has its own static method for that: [regex]::Escape()

Also worth mentioning is that if you read the file including the -Raw switch, so it wil become a single multline string, replacing values is much faster.

$search  = [Regex]::Escape('C:\Program Files (x86)\Adobe\Acrobat Reader 10\Reader\AcroRd32.exe')
$replace = 'C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe'

(Get-Content -Path 'C:\TEMP\App.config' -Raw) -replace $search, $replace | Set-Content -Path 'C:\TEMP\App.config'

Upvotes: 0

Related Questions