Samselvaprabu
Samselvaprabu

Reputation: 18137

How to replace "\" with "\\" using powershell?

I am having a string which contains path.

$Paths = "Myfolder\Mysubfolder"

I need to replace them like "Myfolder\Mysubfolder"

But the $Paths -replace "\","\\" fails as regular expression is unable to find and replace "\".

How to replace then?

Upvotes: 5

Views: 13601

Answers (2)

Allan F
Allan F

Reputation: 2288

I'm thinking an = assignment is required?

$Paths = "Myfolder\Mysubfolder"
write-Host "debug ..... : $Paths"
$Paths = $Paths.Replace("\","\\")
write-Host "debug ..... : $Paths"

This gives:

debug ..... : Myfolder\Mysubfolder
debug ..... : Myfolder\\Mysubfolder

Upvotes: 0

Micky Balladelli
Micky Balladelli

Reputation: 9991

You can use .Replace() which does not use regular expressions like this:

$Paths = "Myfolder\Mysubfolder"
$Paths.replace('\','\\')

To use -replace you will need to escape the slash, since it is regex, on the match and not the substitution with the exception of $1 and $2 ...etc which are used a substitution groups.

$Paths -replace '\\','\\'

Result from both is:

Myfolder\\Mysubfolder

Upvotes: 8

Related Questions