首页 > 解决方案 > 使用 PowerShell 计算 log.file 中字符串的出现次数

问题描述

我需要在日志文件中出现“失败”。问题是我需要为每个会话块获取“失败”的发生。日志的样子:

---第一节
查看
查看
失败
失败
查看
----第二场
查看
失败
查看
查看
----第三节
失败
失败

到目前为止,我得到的是:

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

使用该脚本,我只能得到出现的总数。

标签: stringpowershellpowershell-5.0find-occurrences

解决方案


每当出现以 3 个或更多连续连字符开头的行并将结果收集在哈希表中时,我都会启动一个新计数器。

$failcount = @{}

Get-Content 'E:\shell\lot.log' | ForEach-Object {
    if ($_ -match '^-{3,}(.*)') {
        $section = $matches[1].Trim()
        $failcount[$section] = 0
    } elseif ($_ -like '*failure*') {
        $failcount[$section]++
    }
}

推荐阅读