2015-02-05 125 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