21

I am using -replace to change a path from source to destination. However I am not sure how to handle the \ character. For example:

$source = "\\somedir"
$dest = "\\anotherdir"

$test = "\\somedir\somefile"

$destfile = $test -replace $source, $dest

After this operation, $destfile is set to

"\\\anotherdir\somefile"

What is the correct way to do this to avoid the triple backslash in the result?

timanderson
  • 843
  • 1
  • 10
  • 20

2 Answers2

29

Try the following:

$source = "\\\\somedir"

You were only matching 1 backslash when replacing, which gave you the three \\\ at the start of your path.

The backslash is a regex escape character so \\ will be seen as, match only one \ and not two \\. As the first backslash is the escape character and not used to match.

Another way you can handle the backslashes is use the regex escape function.

$source = [regex]::escape('\\somedir')
Richard
  • 6,812
  • 5
  • 45
  • 60
1

I came here after having issues with Test-Path and Get-Item not working with a UNC path with spaces. Part of the problem was solved here, and the other part was solved as follows:

$OrginalPath = "\\Hostname\some\path with spaces"
$LiteralPath = $OriginalPath -replace "^\\{2}", "\\?\UNC\"

Result: \\?\UNC\Hostname\some\path with spaces

For completeness, putting this into Test-Path returns true (assuming that path actually exists). As @Sage Pourpre says, one needs to use -LiteralPath:

Test-Path -LiteralPath $LiteralPath or Get-Item -LiteralPath $LiteralPath

The replacement operator -replace uses regex.

  • ^ means start of string.
  • \ is the escape character, so we escape the \ with a \.
  • As we have two \'s we tell regex to look for exactly 2 occurrences of \ using {2}.

Instead of using {2}, you can do what @Richard has said and use four \. One escapes the other.

Give it a try here.

woter324
  • 2,608
  • 5
  • 27
  • 47