usr021986
usr021986

Reputation: 3511

String replacement not working in powershell script at runtime

I have powershell file in which i have line of variable decalration as below

[string] $global:myExePath = "\\myshare\code\scripts";

I want to replace \\myshare\code\scripts with \\mynewshare\code1\psscript at runtime by executing a powershell script.

I am using
Get-Content $originalfile | ForEach-Object { $_ -replace "\\myshare\code\scripts", $mynewcodelocation.FullName } | Set-Content ($originalfile)

If am execuing { $_ -replace "scripts", $mynewcodelocation.FullName } it is working fine, but it is not working for { $_ -replace "\\myshare\code\scripts", $mynewcodelocation.FullName }

What is wrong here ?

Upvotes: 2

Views: 6528

Answers (1)

Shay Levy
Shay Levy

Reputation: 126732

'\' is a special regex character used to escape other special character.You need to double each back slash to match one back slash.

-replace "\\\\myshare\\code\\scripts",$mynewcodelocation.FullName 

When you don't know the content of a string you can use the escape method to escape a string for you:

$unc = [regex]::escape("\\myshare\code\scripts")
$unc
\\\\myshare\\code\\scripts

-replace $unc,$mynewcodelocation.FullName 

Upvotes: 5

Related Questions