Home > Enterprise >  Replace Windows Directory Path using -replace that has backslashes in Powershell
Replace Windows Directory Path using -replace that has backslashes in Powershell

Time:10-22

How to treat the blackslashs as not being special to regular expressions?

[string]$users = "C:\Users\dude\"

[string]$path  = "C:\Users\dude\project1\project2"

$i2 = $path -replace $users, ".\"

Message:

The regular expression pattern C:\Users\dude\ is not valid.
char:2
      $i2 = $item -replace "$users", ""
      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  CategoryInfo          : InvalidOperation: (C:\Users\dude:String) [], 
RuntimeException

CodePudding user response:

You can avoid of using regex if you don't need to search something special by regex patterns:

cls
$users = "C:\Users\dude\"
$path  = "C:\Users\dude\project1\project2"

$i2 = $path.Replace($users, ".\")
$i2

# .\project1\project2

By the way, if dude - is your current user, you can use even simpler code:

cls
$path  = "C:\Users\dude\project1\project2"

$i2 = $path.Replace($HOME, ".")
$i2

# .\project1\project2

CodePudding user response:

Mathias R. Jessen's helpful answer answers your question as asked.

Taking a step back: Your task involves removing the verbatim prefix stored in $users from the path stored in $path, so you can simply do:

'.\'   $path.Substring($users.Length)  # -> '.\project1\project2'

In cases where you do need to use a regex and you want prefix matching (matching from the start of the input string), it is generally advisable to anchor the pattern at the start of the string (^) (even though in this particular case there's no risk of false positives; the anchoring also effectively prevents attempts to find multiple matches):

$path -replace ('^'   [regex]::Escape($users)), '.\'

CodePudding user response:

By escaping them:

$path = "C:\Users\dude\project1\project2"
$users = "C:\Users\dude\"
$pattern = [regex]::Escape($users)

$i2 = $path -replace $pattern, ".\"

[regex]::Escape will automatically escape any potential meta-character with a preceding \:

PS ~> [regex]::Escape("C:\Users\dude")
C:\\Users\\dude
  • Related