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 :)
\ 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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With