sam
sam

Reputation: 4684

Passing string included : signs to -Replace Variable in powershell script

$FilePath = 'Z:\next\ResourcesConfiguration.config'
$oldString = 'Z:\next\Core\Resources\'
$NewString = 'G:\PublishDir\next\Core\Resources\'

Any Idea how can you replace a string having : sign in it. I want to change the path in a config file. Simple code is not working for this. tried following

(Get-Content $original_file) | Foreach-Object {
 $_ -replace $oldString, $NewString
 } | Set-Content $destination_file

Upvotes: 1

Views: 1931

Answers (3)

John Bruckler
John Bruckler

Reputation: 122

This works:

$Source = 'Z:\Next\ResourceConfiguration.config'
$Dest = 'G:\PublishDir\next\ResourceConfiguration.config'
$RegEx = "Z:\\next\\Core\\Resources"
$Replace = 'G:\PublishDir\next\Core\Resources'

(Get-Content $FilePath) | Foreach-Object { $_ -replace $RegEx,$Replace } | Set-Content $Dest

The reason that your attempt wasn't working is that -replace expects it's first parameter to be a Regular Expression. Simply put, you needed to escape the backslashes in the directory path, which is done by adding an additional backspace (\\). It expects the second parameter to be a string, so no changes need to be done there.

Upvotes: 0

Shay Levy
Shay Levy

Reputation: 126862

The Replace operator takes a regular expression pattern and '\' is has a special meaning in regex, it's the escape character. You need to double each backslash, or better , use the escape method:

$_ -replace [regex]::escape($oldString), $NewString

Alterntively, you can use the string.replace method which takes a string and doesn't need a special care:

$_.Replace($oldString,$NewString)

Upvotes: 5

CB.
CB.

Reputation: 60938

Try this,

$oldString = [REGEX]::ESCAPE('Z:\next\Core\Resources\')

You need escape the pattern to search for.

Upvotes: 0

Related Questions