使用PowerShell计算log.file中字符串的出现次数

时间:2018-05-23 21:16:58

标签: string powershell powershell-v5.0 find-occurrences

我需要发生"失败"在日志文件中。 问题是我需要发生"失败"对于每个会话块。 日志的样子:

---Session 1 
check 
check 
failure
failure 
check
----Session 2 
check 
failure 
check 
check 
----Session 3 
failure 
failure

到目前为止我得到的是:

$rows = Get-Childitem -Path E:\shell\lot.log  |
        Select-String -Pattern failure
$i = 0
foreach ($row in $rows) {
    $i++
}
echo $i

使用该脚本我只得到总数。

2 个答案:

答案 0 :(得分:0)

我相信这样做会。关键部分是在每次会话后重置你的计数器。

$rows = Get-Childitem -Path E:\shell\lot.log

$i = 0  # failure counter
$j = 1  # session counter

foreach($row in $rows){
    if($row -like "*Session 1"){
        # skip the first line. Edit: removed * as would skip session 10, 11 etc. assumes line ends with "session 1"
        continue
    }elseif($row -eq "failure){
        # if the row is equal to failure, count it
        $i++
    }elseif($row -like "*Session*"){
        # when you get to the end of a session, print the number of failures
        Write-Host "Session $j had $i failures"

        # ... and reset the failure counter 
        $i = 0

        # increment the session counter
        $j++
    }
}

答案 1 :(得分:0)

我会添加另一个选项。使用-Raw读取整个日志文件以获取多行字符串。从第一行中删除----,然后在一行的开头拆分3个或更多个连字符,这会将每个会话作为多行字符串,然后您可以只输出文本或自定义对象,或者其他你想要它。在新行字符上拆分多行字符串,过滤“失败”,并进行计数以获得每个会话的失败。

(GC E:\shell\lot.log -Raw) -replace '^-+' -split '(?<=[\r\n])---+'|%{
    '{0} had {1} failure(s)' -f ($_.split("`n")[0].Trim()),($_ -split '[\r\n]+'|?{$_ -match 'failure'}).Count
}

那会(给出样本提供)输出:

Session 1 had 2 failure(s)
Session 2 had 1 failure(s)
Session 3 had 2 failure(s)