You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell统计多格式日志指定日期区间错误并导出TXT咨询

实现方案

需求完全可以实现,你现有脚本存在几处不符合需求的问题,调整后即可满足要求。

现有脚本问题

  • 未遍历指定日志目录下的所有符合后缀要求的日志文件,仅引用了未定义的$tempfile变量
  • 正则匹配规则和实际日志的日期格式(MM/dd/yy)不匹配,无法正确提取日志时间
  • 日期范围判断逻辑写反,无法正确筛选指定时间段内的日志
  • 未保留原始日志行内容,无法输出你需要的错误明细
  • 未对指定错误类型(华硕/微软等对应你说的$err1/$err2)做兜底计数,没有0错误的展示逻辑
  • 未实现执行完成后自动打开生成的统计文件的逻辑

修改后完整脚本

$TodaysDate = Get-Date -UFormat "%d.%m.%Y %R"
$logFolder = "C:\Users\bogda\OneDrive\Desktop\TestFolder"
$outputFile = Join-Path $logFolder "Machine_Errors.txt"

# 错误类型映射,可自行扩展
$errTypeMap = @{
    'ASUS' = '$err1'
    'Microsoft' = '$err2'
}

function Read-Date {
  param(
    [String] $prompt
  )
  $result = $null
  do {
    $s = Read-Host $prompt
    if ( $s ) {
      try {
        $result = Get-Date $s
        # 时间取0点方便比较整日
        $result = $result.Date
        break
      }
      catch [Management.Automation.PSInvalidCastException] {
        Write-Host "Date not valid"
      }
    }
    else {
      break
    }
  }
  while ( $true )
  $result
}

Write-Host "Astazi este data de $TodaysDate"
$startDate = Read-Date "Enter Start Date"
$endDate = Read-Date "Enter End Date"
# 结束日期取23:59:59覆盖整天
$endDate = $endDate.Date.AddDays(1).AddSeconds(-1)

# 遍历所有符合后缀的日志文件
$logFiles = Get-ChildItem -Path $logFolder -File | Where-Object {
    $_.Name -match 'log\.0$|log\.jrn$'
}

$output = @()
foreach ($file in $logFiles) {
    switch -Regex -File $file.FullName {
        # 匹配带厂商错误标识、同时带日期的行
        '(.*(Asus|Microsoft):\d{2}:\d{2}:\d{2}).*(\d{2}/\d{2}/\d{2})\s+(\d{2}:\d{2}:\d{2})[a|p]?' {
            $rawLine = $_.Trim()
            $vendor = $matches[2].Trim()
            $dateStr = $matches[3].Trim()
            $timeStr = $matches[4].Trim()

            try {
                $logTime = [datetime]::ParseExact("$dateStr $timeStr", 'MM/dd/yy HH:mm:ss', $null)
            }
            catch {
                # 时间解析失败直接跳过
                continue
            }

            # 校验日期范围
            if ($logTime -lt $startDate -or $logTime -gt $endDate) {
                continue
            }

            # 规范化厂商名称
            $vendorStandard = switch ($vendor.ToLower()) {
                'asus' {'ASUS'}
                'microsoft' {'Microsoft'}
                default {'Unknown'}
            }

            $output += [PSCustomObject]@{
                Vendor = $vendorStandard
                ErrType = $errTypeMap[$vendorStandard]
                Date = $logTime.ToString('dd.MM.yyyy')
                Time = $logTime.ToString('HH:mm')
                RawLine = $rawLine
                FileName = $file.Name
            }
        }
    }
}

# 生成输出内容
$outputContent = @()
# 遍历所有定义的错误类型,保证0错误的也会输出
foreach ($type in $errTypeMap.GetEnumerator()) {
    $vendor = $type.Key
    $errTag = $type.Value
    $errItems = $output | Where-Object {$_.Vendor -eq $vendor}
    $count = $errItems.Count

    $outputContent += "***$count errors $errTag***"
    $outputContent += "     Details:"
    if ($count -gt 0) {
        # 按日期分组统计
        $dateGroups = $errItems | Group-Object -Property Date
        foreach ($dGroup in $dateGroups) {
            $times = $dGroup.Group.Time -join ', '
            $outputContent += "     $($dGroup.Count) errors in $($dGroup.Name) - $times"
            # 按文件名分组展示原始日志
            $fileGroups = $dGroup.Group | Group-Object -Property FileName
            foreach ($fGroup in $fileGroups) {
                $outputContent += "     $($fGroup.Name) :"
                foreach ($line in $fGroup.Group.RawLine) {
                    $outputContent += "        $line"
                }
            }
        }
    }
    else {
        $outputContent += "     0 errors in $($startDate.ToString('dd.MM.yyyy'))"
    }
    $outputContent += ""
}

# 写入文件并打开
Set-Content -Path $outputFile -Encoding UTF8 -Value $outputContent
Start-Process notepad.exe $outputFile

适配说明

  • 可自行扩展$errTypeMap添加更多错误类型和对应厂商的映射
  • 如果日志格式有变动,调整switch块内的正则匹配规则即可
  • 自动过滤时间解析失败的无效行,不会中断脚本运行

内容的提问来源于stack exchange,提问作者SySx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 23:18:01