Powershell提取最近n分钟的日志文件内容

时间:2020-05-25 14:50:07

标签: powershell date parsing logging select-string

我试图在最近n分钟内从日志文件中提取内容,并根据提取的数据执行另一组操作。我的日志文件如下所示:

2019-01-25 02:45:55,018 [5 - -22d] INFO Server - Some information
2019-01-25 02:45:55,018 [5 - -22d] INFO Server - Some information
2019-02-25 02:45:55,018 [5 - -22d] INFO Server - Some information
2019-02-25 19:09:50,018 [5 - -22d] ERROR IOException Some Error
2019-02-25 02:45:55,018 [5 - -22d] INFO Server - Some information

我创建了一个任务调度程序,该任务调度程序每1分钟运行一次,并在最近1分钟内检查日志文件中的特定错误,然后执行下一步操作。这里重要的是时间,我想将当前时间与错误发生时的日志文件时间。我尝试过的是:

 $data=Get-Content $log | Select-String -Pattern 'String to search error'
   foreach ($line in $data){
     $logdate = Get-Date ($line -split ',')[0] -Format 'yyyy-MM-dd HH:mm'
      Write-Output $logdate
       if($date -eq $logdate){
          Write-Output "Some action"          
       }   
   }

是否有更好的方法来达到相同的结果?因为我对Powershell不太熟悉,所以社区可以公开一些吗?还尝试了其他各种cmdlet“ LastWriteTime,Get-Content,regex-等”

2 个答案:

答案 0 :(得分:1)

还有其他替代方法。

将找到的每个日期转换为DateTime对象,并与某个参考日期进行比较。使用-like将搜索限制为仅包含指定搜索词的行。

$referenceTime  = (Get-Date '2019-02-25 19:09:00').AddMinutes(-10)
$wildcardSearch = '*ERROR*'
Get-Content -Path 'D:\SomeLog.log' | 
Where-Object { $_ -like $wildcardSearch -and (Get-Date ($_ -split ',')[0]) -gt $referenceTime }
ForEach-Object { 
    # do something here, for demo just output the 
    $_
}

或者,由于日期和时间都是可排序的格式,因此您不必转换为DateTime。 该演示使用正则表达式-match比较搜索字词

# the reference time in sortable string format, as are the dates in the log
$referenceTime = '{0:yyyy-MM-dd HH:mm:ss}' -f (Get-Date '2019-02-25 19:09:00').AddMinutes(-10)
# simple words like ERROR do not need escaping, but other search terms might
$regexSearch   = [regex]::Escape('ERROR') 
Get-Content -Path 'D:\SomeLog.log' | 
Where-Object { $_ -match $regexSearch -and ($_ -split ',')[0] -gt $referenceTime } |
ForEach-Object { 
    # do something here, for demo just output the 
    $_
}

或者,使用最快的方式遍历日志中的各行(再次使用Regex):

$referenceTime = '{0:yyyy-MM-dd HH:mm:ss}' -f (Get-Date '2019-02-25 19:09:00').AddMinutes(-10)
$regexSearch   = [regex]::Escape('ERROR') 
switch -Regex -File 'D:\SomeLog.log' {
    $regexSearch { 
        if (($_ -split ',')[0] -gt $referenceTime) { 
            # do something here, for demo just output the line
            $_ 
        }
    }
}

答案 1 :(得分:-1)

在第一次运行服务之前,请确保以管理员身份运行powershell脚本并启动该脚本。

当以下代码为“ ERROR IOException”时,它们将继续重新启动服务

Get-Content -Tail 0 -Path $log -Wait | % {
    if($_ -like "*ERROR IOException*"){ # use * as wildcards
        write-host $_ -ForegroundColor Red
        write-host Restart your service
        Restart-Service -Name "__NAME OF YOUR SERVICE__" -Force
    }
}