Reputation: 4736
Been trying various combinations but I just cannot replace the text I want below - I keep on getting an error. I have a feeling it does not like the "\" or even the "$" I have added but cannot see what is wrong - any help would be appreciated. All I want to do is to replace some text to something else.
PS C:\> $f = "C:\LocalGAR\WIN\Comp\register\x86_v1.0"
PS C:\> $f -replace ('C:\LocalGAR','\\comp.gci.tk.com\files$')
The regular expression pattern C:\LocalGAR is not valid.
At line:1 char:1
+ $f -replace ('C:\LocalGAR','\\comp.gci.tk.com\files$')
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (C:\LocalGAR:String) [], RuntimeException
+ FullyQualifiedErrorId : InvalidRegularExpression
Upvotes: 1
Views: 280
Reputation: 118
Have you tried calling 'replace' as a method like so:
$f.replace('C:\LocalGAR','\\comp.gci.tk.com\files$')
This doesn't throw an error for me where your line does.
EDIT (from Mathias R. Jessen):
Yes it is also good to note that "-replace"
is completely different to ".replace"
Upvotes: 2
Reputation: 29048
PowerShell's -replace
operator uses regular expressions for pattern matching, and they use backslash \
to identify regular expression groups - e.g. \s
is "any whitespace character (spaces, tabs)".
It's trying to match \L
to a regular expression command, and can't find it, and is throwing an error.
The replace text for -replace
is a normal string, not a regex, so the $
is fine in there.
(The two options, as given by the other answers, are to use the $string.replace()
method which does literal string replacement, or to escape the special characters in the regex so they are not commands - either by hand or with [regex]::escape()
).
Upvotes: 1
Reputation: 58491
You have to escape the slashes in your search pattern
manually escaped
$f -replace ('C:\\LocalGAR','\\comp.gci.tk.com\files$')
or the safer automatic escaped string
$f -replace ([Regex]::Escape('C:\LocalGAR'),'\\comp.gci.tk.com\files$')
returns
\\comp.gci.tk.com\files$\WIN\Comp\register\x86_v1.0
Upvotes: 2