首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用PowerShell select-string在文件中查找多个模式?

如何使用PowerShell select-string在文件中查找多个模式?
EN

Stack Overflow用户
提问于 2010-10-13 10:23:21
回答 3查看 127K关注 0票数 32

我想在一个目录的文件中搜索多个字符串,但是使用"select-string -pattern“没有帮助。有人能教我怎么做吗?

示例:搜索C:\Logs中包含单词"VendorEnquiry“和"Failed”的所有文件,日志时间为上午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> ...

谢谢。

EN

回答 3

Stack Overflow用户

发布于 2011-01-08 03:22:55

如果您希望以任意顺序匹配这两个单词,请使用:

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

如果失败总是出现在行的VendorEnquiry之后,只需使用:

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

Stack Overflow用户

发布于 2011-10-16 23:22:25

要在每个文件中搜索多个匹配项,我们可以对几个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',...

现在,为了满足示例中的"Logtime about 11:30am“部分,需要找到对应于每个失败条目的日志时间。如何做到这一点高度依赖于文件的实际结构,但对"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
票数 27
EN

Stack Overflow用户

发布于 2018-07-24 01:53:12

您可以在一个数组中指定多个模式。

select-string VendorEnquiry,Failed C:\Logs

这也适用于-notmatch:

select-string -notmatch VendorEnquiry,Failed C:\Logs
票数 17
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3920383

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档