PowerShell需求:按文件递归统计各4位ErrorID的出现次数
按文件统计每个4位ErrorID的出现次数
用这条PowerShell命令就能实现需求:
Get-ChildItem -File -Recurse | ForEach-Object { $filePath = $_.FullName Select-String -Path $filePath -Pattern 'ErrorID:(\d{4})' | ForEach-Object { $_.Matches.Groups[1].Value } | Group-Object | ForEach-Object { [PSCustomObject]@{ FileName = $filePath ErrorID = $_.Name Count = $_.Count } } } | Format-Table FileName, ErrorID, Count -AutoSize
命令拆解
Get-ChildItem -File -Recurse:递归遍历目标目录下的所有文件Select-String -Pattern 'ErrorID:(\d{4})':匹配带4位数字的ErrorID,通过括号捕获组提取纯数字IDGroup-Object:对每个文件提取到的ErrorID分组统计出现次数- 自定义
PSCustomObject:统一输出包含文件名、ErrorID、次数的结构化数据 Format-Table -AutoSize:自动调整列宽,让输出更易读
对应示例输入的输出效果
FileName ErrorID Count ---------- ------- ----- D:\test\log1.txt 3211 2 D:\test\log1.txt 4443 1 D:\test\log2.txt 5588 1 D:\test\log2.txt 4443 2
如果需要导出结果到CSV文件方便后续分析,把最后一行的Format-Table替换成:
Export-Csv -Path "ErrorID_Statistics.csv" -NoTypeInformation
内容的提问来源于stack exchange,提问作者Sam
相关产品推荐
相关产品推荐

