Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble escaping backslashes using replace

I am looking to use the PowerShell replace function to replace part of a network path. I am having troubles with how to handle backslashes (\)

"\\Share\Users\Location\Username" -ireplace  "\\Share\Users","\\NewShare\AllUsers"

The above code will produce an error, so I looked at escaping using [Regex]::Escape but it will not replace the text:

[Regex]::Escape( "\\Share\Users\Location\Username") -ireplace  [Regex]::Escape("\\Share\Users"),[Regex]::Escape("\\NewShare\AllUsers")

This is what I get:

\\\\Share\\Users\\Location\\Username

All I need is:

\\Share\Users replaced by \\NewShare\AllUsers to produce \\NewShare\AllUsers\Location\Username

My knowledge is limited for regular expressions at the moment, so I was wondering if someone could kindly help me :)

like image 956
user2142466 Avatar asked Mar 15 '26 11:03

user2142466


2 Answers

\ is a special character in regex, and \U in \Users causes it to look for a special command U which doesn't exist. You need to escape the backslashes:

"\\Share\Users\Location\Username" -ireplace  "\\\\Share\\Users", "\\NewShare\AllUsers"

Basically [RegEx]::Escape() was the right approach but the key is to only use it on the parameters that are actually regular expressions (the second one).

like image 125
TessellatingHeckler Avatar answered Mar 17 '26 01:03

TessellatingHeckler


You should be able to use ireplace, just adjust your first parameter like so:

"\\Share\Users\Location\Username" -ireplace  "\\\\Share\\Users","\\NewShare\AllUsers"

Notice I had to escape the backslashes because that is treated as a regex whereas the first and 3rd parameters are treated as strings.

like image 36
Sam Avatar answered Mar 17 '26 00:03

Sam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!