首页 > 解决方案 > Powershell CSV 导入。如果用户名匹配,则将值相加

问题描述

我有以下已导入 Powershell 数组的 CSV 文件

  User     Today  MTD
  ----     -----  ---
  User1    5      15
  User1    3      32
  User2    2      5
  User1    1      23
  User2    3      34
  User3    3      34

如果用户匹配,我想将 Today 和 MTD 数字添加到一行

示例:用户 1 将是“今天”5+3+1=9“MTD”15+32+23=70

所需输出:

  User     Today  MTD
  ----     -----  ---
  User1    9      70
  User2    5      39
  User3    3      34

我可以使用列出一个用户名的数据


$arr.Where({$_.User -eq "user1"})

但不知道如何将今天和 MTD 加在一起

标签: arrayspowershellmultidimensional-arraycsv-import

解决方案


There you go, I answered a very similar question here.

Code:

$csv = @'
User,Today,MTD
User1,5,15
User1,3,32
User2,2,5
User1,1,23
User2,3,34
User3,3,34
'@ | ConvertFrom-Csv

$csv | Group-Object User | ForEach-Object {
    $_.Group[0].Today = ($_.Group.Today | Measure-Object -Sum).Sum
    $_.Group[0].MTD = ($_.Group.MTD | Measure-Object -Sum).Sum
    $_.Group[0]
}

Output:

User  Today MTD
----  ----- ---
User1     9  70
User2     5  39
User3     3  34

Edit

To export the results you can do this:

$csv | Group-Object User | ForEach-Object {
    # Original code here...
} | Export-Csv newCsv.csv -NoTypeInformation

Or this if you want to preserve the new object in memory:

$newCsv = $csv | Group-Object User | ForEach-Object {
    # Original code here...
}

$newCsv | Export-Csv newCsv.csv -NoTypeInformation

推荐阅读