【问题标题】:Powershell: regex on Get-EventLog output and find largest numberPowershell:Get-EventLog输出上的正则表达式并找到最大的数字
【发布时间】:2013-05-21 04:54:53
【问题描述】:

我需要从这个命令的输出中提取一个特定的数字:

Get-EventLog "application" | Where-Object {$_.EventID -eq 6006}

示例输出为:

Index Time          EntryType   Source                 InstanceID Message
----- ----          ---------   ------                 ---------- -------
18297 May 15 18:49  Warning     Wlclntfy               2147489654 The winlogon notification subscriber <Profiles> took 60 second(s) to handle the notification event (Logon).
11788 Jan 31 08:11  Warning     Wlclntfy               2147489654 The winlogon notification subscriber <Profiles> took 68 second(s) to handle the notification event (Logon).
5794 Oct 16 09:41  Warning     Wlclntfy               2147489654 The winlogon notification subscriber <Sens> took 225 second(s) to handle the notification event (Logoff).
5596 Oct 11 08:03  Warning     Wlclntfy               2147489654 The winlogon notification subscriber <Profiles> took 69 second(s) to handle the notification event (Logon).
2719 Aug 30 07:50  Warning     Wlclntfy               2147489654 The winlogon notification subscriber <Profiles> took 65 second(s) to handle the notification event (Logon).

我真正需要做的是拉出&lt;Profiles&gt;事件报告的秒数,并拉出最大的一个。我已经弄清楚(?&lt;=&lt;Profiles&gt; took )(\d+) 将努力提取我需要的数字,但我不确定如何继续实际提取它们。我已经尝试将它通过管道传递给 Select-String -pattern,但这根本不返回任何内容。

【问题讨论】:

  • 您需要编写一个循环并不断比较正则表达式返回的数字以找到最大的数字。 AFAIK,正则表达式不能返回最大的数字:)

标签: regex powershell


【解决方案1】:

您需要 $matches 内置变量。 $matches[0] 是匹配正则表达式的文本,$matches[1] .. $matches[n] 是匹配的括号表达式(如果有的话)。 遗憾的是,我的机器上没有任何 EventID=6006,所以我在没有测试的情况下这样做,但这应该从排序的秒列表中选择最后一项:

Get-EventLog "application" | 
    Where-Object {$_.EventID -eq 6006} | 
    Where-Object { $_.Message -match "<Profiles> took (\d*) second" } |
    foreach { [int]$matches[1] } |
    sort |
    select -last 1

【讨论】:

    【解决方案2】:

    您可以在没有正则表达式的情况下获取值。查看事件的 ReplacementStrings 属性。它包含一个数组,其中包含存储在事件条目中的替换字符串。

    PS> $event.ReplacementStrings
    Profiles
    71
    Logon
    

    基于此,您可以使用数组索引来获取您所追求的值。

    Get-EventLog application | 
    Where-Object {$_.EventID -eq 6006 -and $_.ReplacementStrings -eq 'Profiles'} | 
    Foreach-Object { $_.ReplacementStrings[1] }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-09
      • 1970-01-01
      • 1970-01-01
      • 2016-06-12
      • 2021-10-22
      • 2020-02-29
      • 1970-01-01
      • 2016-06-13
      相关资源
      最近更新 更多