2015-02-05 138 views
2

我试图搜索目录c:\bats\包含UNC路径的批处理文件\\server\public选择字符串转义字符

命令:

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

我收到相关的字符串\\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 

我试过使用各种转义,如"\server\public""'\server\public'",但我总是收到t帽子同样的错误。

回答

3

尝试使用单引号围绕您的搜索字符串并指定SimpleMatch。

Get-ChildItem -path c:\bats\ -recurse | Select-string -pattern '\\server\public' -SimpleMatch 
+0

谢谢,这就像一个魅力工作! – rob 2015-02-05 20:52:17

+0

如果模式是可变的,该怎么办? – 2018-02-05 15:48:30

3

由于解决方案在@campbell.rw的答案中,所以要扩展更多的问题。 Select-String参数-Pattern支持正则表达式。反斜杠是一个控制字符,需要转义。这不是你需要从PowerShell中转义它,而是从正则表达式引擎本身。转义字符也是反斜杠

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

您可以使用regex类中的静态方法为您完成这项艰巨工作。

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

再次,在你的情况下,使用-SimpleMatch是一个更好的解决方案。

+0

谢谢你的澄清! – rob 2015-02-05 20:53:01