8

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.

Matt
  • 45,022
  • 8
  • 78
  • 119
rob
  • 81
  • 1
  • 1
  • 3

2 Answers2

8

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.

Matt
  • 45,022
  • 8
  • 78
  • 119
7

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

Get-ChildItem -path c:\bats\ -recurse | Select-string -pattern '\\server\public' -SimpleMatch
campbell.rw
  • 1,366
  • 12
  • 22
  • what if the pattern is in variable ? –  Feb 05 '18 at 15:48
  • @ShreedharDhanawade I don't know about your situation but I found that my issue was that I was accidentally using a variable that was an array for the match. I narrowed to a string and that solved the problem. – duct_tape_coder Oct 23 '18 at 17:37