如何使用 PowerShell 选择字符串在文件中查找多个模式?

问题描述 投票:0回答:3

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

示例: 搜索 C:\Logs 中包含单词“VendorEnquiry”和“Failed”且 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> ...

谢谢。

powershell
3个回答
44
投票

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

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

如果线路上的 VendorEnquiry 之后总是出现 Failed,只需使用:

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

35
投票

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

29
投票

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

Select-String -Pattern @('VendorEnquiry', 'Failed') -LiteralPath "$Env:SystemDrive\Logs"

这也适用于

-NotMatch

Select-String -NotMatch @('VendorEnquiry', 'Failed') -LiteralPath "$Env:SystemDrive\Logs"
© www.soinside.com 2019 - 2024. All rights reserved.