If you want Select-String
to match literals (literal substring matching) rather than (by default) regular expressions, use -SimpleMatch
:
Select-String -SimpleMatch -Pattern $SearchStr -Path $env:SystemRoot\win.ini
By contrast, if you need to incorporate a literal into a regular expression, apply [regex]::Escape()
to it, as TessellatingHeckler suggests.
E.g., to only find $SearchStr
at word boundaries (\b
):
Select-String -Pattern ('\b' + [regex]::Escape($SearchStr) + '\b') -Path $env:SystemRoot\win.ini
Optional background information
By default, Select-String
interprets the search terms passed to parameter -Pattern
as regexes (regular expressions).
In regular expressions, \
has special meaning: it is used as the escape character to modify how the regular-expression engine would otherwise interpret the following character(s).
Therefore, the \
in Windows-style paths such as c:\programFiles\xyz
results in interpretation of the \
chars. as the start of an escape sequence.
Using the sample path: \p
, if followed by a Unicode character category such as {L}
, matches any character in that category; \x
, if followed by 2 hexadecimal digits, matches a single character with that code point.
To escape \
itself, so that it is treated literally, double it: \\
.
The .NET framework [regex]::Escape()
method can do this for you, along with escaping any other characters that have special meaning to the regex engine.
In other words: to embed a literal string in a regular expression, pass it to [regex]::Escape()
first.