Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select-string escape character

I'm trying to search directory c:\bats\ for batch files containing the unc path \\server\public

Command:

Get-ChildItem -path c:\bats\ -recurse | Select-string -pattern "\\server\public"

I receive an error related to the string \\server\public:

Select-string : The string \\server\public is not a valid regular
expression: parsing "\\server\public" - Malformed \p{X} character
escape. At line:1 char:91
+ ... ts" -recurse | Select-string -pattern \\server\public
+                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidArgument: (:) [Select-String], ArgumentException
+ FullyQualifiedErrorId : InvalidRegex,Microsoft.PowerShell.Commands.SelectStringCommand

I've tried using various escapes such as "\server\public" or "'\server\public'" but I always receive that same error.

like image 785
rob Avatar asked Feb 05 '15 14:02

rob


People also ask

How do you escape characters in a string?

\ is a special character within a string used for escaping. "\" does now work because it is escaping the second " . To get a literal \ you need to escape it using \ .

How do I escape a character in SQL query?

In ANSI SQL, the backslash character (\) is the escape character. To search for data that begins with the string \abc , the WHERE clause must use an escape character as follows: ... where col1 = '\\abc';

How do you escape special characters in a string in PowerShell?

This means that if you hard code a Distinguished Name in PowerShell, and the string is enclosed in double quotes, any embedded double quotes must be escaped first by a backtick "`", and then by a backslash "\".

What is \u escape character?

A unicode escape sequence is a backslash followed by the letter 'u' followed by four hexadecimal digits (0-9a-fA-F). It matches a character in the target sequence with the value specified by the four digits. For example, ”\u0041“ matches the target sequence ”A“ when the ASCII character encoding is used.


2 Answers

Try this using single quotes around your search string and specifying SimpleMatch.

Get-ChildItem -path c:\bats\ -recurse | Select-string -pattern '\\server\public' -SimpleMatch
like image 169
campbell.rw Avatar answered Oct 30 '22 21:10

campbell.rw


To expand more on the problem since the solution is in @campbell.rw's answer. The Select-String parameter -Pattern supports regular expressions. The backslash is a control character and needs to be escaped. It is not that you need to escape it from PowerShell but the regex engine itself. The escape character is also a backslash

Select-string -pattern '\\\\server\\public'

You can use a static method from the regex class to do that hard work for you.

Select-string -pattern ([regex]::Escape('\\server\public'))

Again, in your case, using the -SimpleMatch is a better solution.

like image 32
Matt Avatar answered Oct 30 '22 19:10

Matt