Reputation: 105
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 :)
Upvotes: 3
Views: 55
Reputation: 29033
\
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).
Upvotes: 4
Reputation: 543
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.
Upvotes: 1