基于Action字段匹配累加CSV中Count值的PowerShell实现求助
PowerShell 实现动作计数CSV累加与追加逻辑完善
需求说明
- 每30分钟导入新旧两份CSV文件,合并动作计数数据
- 匹配
Action列值时,将新CSV的Count累加到旧CSV对应行的Count - 无匹配
Action值时,将新CSV的该行追加到旧CSV末尾 - 新文件会覆盖旧文件,可手动复制旧文件留存历史版本
数据示例
新CSV文件(ActionReport_Count_New.csv)
Count,Action 6,Apples 5561,Oranges 5,Bananas 324,Kiwis 8,Grapefruits
原始旧CSV文件(ActionReport_Count.csv)
Count,Action 14,Apples 1,Pomegranate 5205,Oranges 491,Kiwis 1,Grapefruits
合并后目标CSV文件
Count,Action 20,Apples 1,Pomegranate 10766,Oranges 5,Bananas 815,Kiwis 9,Grapefruits
完善后的代码
# 定位脚本所在目录 $scriptPath = Split-Path -Parent $MyInvocation.MyCommand.Definition Set-Location -Path $scriptPath # 定义文件路径(用Join-Path替代字符串拼接,避免路径格式错误) $originalCSVPath = Join-Path -Path $scriptPath -ChildPath "Output\ActionReport_Count.csv" $newCSVPath = Join-Path -Path $scriptPath -ChildPath "Output\ActionReport_Count_New.csv" # 导入CSV并转换Count为数值类型,避免字符串拼接错误 $originalData = Import-CSV -Path $originalCSVPath -Delimiter "," | ForEach-Object { [PSCustomObject]@{ Count = [int]$_.Count Action = $_.Action } } $newData = Import-CSV -Path $newCSVPath -Delimiter "," | ForEach-Object { [PSCustomObject]@{ Count = [int]$_.Count Action = $_.Action } } # 核心逻辑:处理新数据的累加与追加 foreach ($newRow in $newData) { # 查找旧数据中匹配的Action行 $matchRow = $originalData | Where-Object { $_.Action -eq $newRow.Action } if ($matchRow) { # 找到匹配项,累加Count值 $matchRow.Count += $newRow.Count } else { # 无匹配项,追加新的动作记录 $originalData += $newRow } } # 将更新后的数据导出回原CSV(覆盖旧文件),-NoTypeInformation避免生成多余类型行 $originalData | Export-CSV -Path $originalCSVPath -Delimiter "," -NoTypeInformation
关键说明
- 类型转换:强制将
Count转为整数类型,彻底避免字符串拼接导致的错误(比如"14"+"6"变成"146") - 高效匹配:用
Where-Object替代嵌套循环,简化逻辑同时提升处理效率 - 数据更新:直接修改原始数据集合的匹配行计数,无匹配则追加新行
- 规范导出:使用
-NoTypeInformation参数,保证导出的CSV格式纯净,没有PowerShell自动添加的类型头
内容的提问来源于stack exchange,提问作者MichaelH
相关产品推荐
相关产品推荐

