如何使用PowerShell select-string在文件中查找多个模式?
问题描述:
我想在目录中的文件中搜索多个字符串,但使用“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> ...
谢谢。
答
如果你想匹配任何顺序,使用这两个词:
gci C:\Logs| select-string -pattern '(VendorEnquiry.*Failed)|(Failed.*VendorEnquiry)'
如果失败总是VendorEnquiry上线后,只需使用:
gci C:\Logs| select-string -pattern '(VendorEnquiry.*Failed)'
答
要搜索我们可以对几个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