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