要在每个文件中搜索多个匹配项,我们可以对多个 Select-String 调用进行排序:
Get-ChildItem C:\Logs |
where { $_ | Select-String -Pattern 'VendorEnquiry' } |
where { $_ | Select-String -Pattern 'Failed' } |
...
在每个步骤中,将过滤掉不包含当前模式的文件,确保最终的文件列表包含所有搜索词。
与其手动写出每个 Select-String 调用,我们可以使用过滤器来简化它以匹配多个模式:
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',...
现在,要满足示例的“大约上午 11:30 的日志时间”部分,需要找到与每个失败条目对应的日志时间。如何做到这一点高度依赖于文件的实际结构,但测试“about”相对简单:
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