5

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?

2 Answers 2

8

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
Sign up to request clarification or add additional context in comments.

2 Comments

Hey Micky.... please try and make your answers with a little more explanation than "try this" or "does this work"
The substitution string does use a few (one?) regex metacharacters for specifying substitution groups such as $1 $2.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.