2014-01-09 145 views
1

我想微調我的腳本,並想看看我是否能得到它的幫助。我目前已經編寫了腳本來搜索輸入目錄中的文件,但是它會搜索部分搜索條件而不是完全匹配。例子...我正在尋找搶劫,但是我的搜索返回搶劫,羅伯特和羅伯塔......我需要確保當我搜索搶劫時,它只會返回搶劫。任何幫助將不勝感激。Powershell精確搜索結果

#Requests the loctation of the files to search 
$Location = Read-Host 'What is the folder location of the files you want to search?'  

#Sets the location based off of the above variable 
Set-Location $Location 

#1. Goes thru all the files and subfiles looking for all .sql 
$ItemList = Get-ChildItem -Path $Location -Filter *.sql -Recurse; 

#2. Define the search parameters 
$Search1 = Read-Host 'First Object Name?'; 
$Search2 = Read-Host 'Second Object Name?'; 

#3. For each item returned in step 1, check to see if it matches both strings 
foreach ($Item in $ItemList) { 
$Content = $null = Get-Content -Path $Item.FullName -Raw; 
if ($Content -match $Search1 -and $Content -match $Search2) { 
    Write-Host -Object ('File ({0}) matched both search terms' -f $Item.FullName); 
} 
} 

#Sets location back to root 
Set-Location C: 

Write-Host "Press any key to continue ..." 

$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") 
+0

是否有被使用的一些nameing語法?如果$ serach1是'rob'並且$ search2是'berta',它應該返回什麼? – mjolinor

+0

基本上它用於查找具有多個搜索條件的文檔。我用它來搜索SQL文件的表名和列名。如果文件同時包含表名和列名,那麼這就是我想看到的。 –

回答

4

對於需要匹配單詞邊界精確匹配(\b):

if ($Content -match "\b$Search1\b" -and $Content -match "\b$Search2\b") { 
    ... 
} 

有一些字符(所謂的元字符)在正則表達式有特殊的含義,例如\,^或方括號。如果你想在你的搜索詞都被當作你應該考慮在有條件使用前逃離這些條款的文字字符:

$Search1 = [regex]::Escape($Search1) 
$Search2 = [regex]::Escape($Search2) 
+0

這很好。感謝Ansgar的快速反應。我知道這很簡單,只是不知道如何完成。 –

+2

爲了使其完美無瑕,您應該首先使用正則表達式逃避用戶輸入以支持特殊字符。你永遠不知道用戶可能會做什麼:-)'$ Content -match「\ b $([regex] :: Escape($ Search1))\ b」....' –

+0

Powershell + Sql意味着Sql Server,其中括號當對象名稱是保留字或有空格時使用。 – vonPryz