2010-10-13 70 views
19

我想在目錄中的文件中搜索多個字符串,但使用「select-string -pattern」沒有幫助。任何人都可以告訴我該怎麼做?如何使用PowerShell select-string在文件中查找多個模式?

例如:搜索包含單詞「VendorEnquiry」和「Failed」的C:\ Logs中的所有文件,並且Logtime約爲上午11:30。文件結構可能不同(例如不同的標籤名稱等):

... <methodException>VendorEnquiry</methodException> ... 
... <logTime>13/10/2010T11:30:04 am</logTime> ... 
... <status>Failed</status> ... 

... <serviceMethodException>VendorEnquiry</serviceMethodException> ... 
... <logTime>13/10/2010</logTime> ... 
... <serviceStatus>Failed</serviceStatus> ... 

謝謝。

回答

0
+0

我不想使用XML解析造成鉅額日誌文件很慢的性能。我想要的東西很快。正則表達式是好的,但我不知道如何編寫表達式搜索文件中有一個單詞VendorEnquiry和Failed exists。 – Thomas 2010-10-13 05:32:01

22

如果你想匹配任何順序,使用這兩個詞:

gci C:\Logs| select-string -pattern '(VendorEnquiry.*Failed)|(Failed.*VendorEnquiry)' 

如果失敗總是VendorEnquiry上線後,只需使用:

gci C:\Logs| select-string -pattern '(VendorEnquiry.*Failed)' 
16

要搜索我們可以對幾個Select-String調用進行排序:

Get-ChildItem C:\Logs | 
    where { $_ | Select-String -Pattern 'VendorEnquiry' } | 
    where { $_ | Select-String -Pattern 'Failed' } | 
    ... 

在每一步中,不包含當前模式的文件都將被過濾掉,確保最終的文件列表包含所有搜索項。

而不是手工編寫出每個選擇串電話,我們可以用一個過濾器簡化了這一匹配多個模式:

filter MultiSelect-String([string[]]$Patterns) { 
    # Check the current item against all patterns. 
    foreach($Pattern in $Patterns) { 
    # If one of the patterns does not match, skip the item. 
    $matched = @($_ | Select-String -Pattern $Pattern) 
    if(-not $matched) { 
     return 
    } 
    } 

    # If all patterns matched, pass the item through. 
    $_ 
} 

Get-ChildItem C:\Logs | MultiSelect-String 'VendorEnquiry','Failed',... 


現在,爲了滿足「LOGTIME約11:30」的一部分該示例需要查找與每個失敗條目對應的日誌時間。如何做到這一點是高度依賴於文件的實際結構,但對於測試「約」是比較簡單的:

function AboutTime([DateTime]$time, [DateTime]$target, [TimeSpan]$epsilon) { 
    $time -le ($target + $epsilon) -and $time -ge ($target - $epsilon) 
} 

PS> $epsilon = [TimeSpan]::FromMinutes(5) 
PS> $target = [DateTime]'11:30am' 
PS> AboutTime '11:00am' $target $epsilon 
False 
PS> AboutTime '11:28am' $target $epsilon 
True 
PS> AboutTime '11:35am' $target $epsilon 
True 
相關問題