arrayspowershellmultidimensional-arraycsv-import

Powershell CSV Import. Adding values together if username match


I have the following CSV file that I have imported into Powershell array

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

If the user matches I would like to add the Today and MTD figures to one line

Example: User1 would be "Today" 5+3+1=9 "MTD" 15+32+23=70

Required output:

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

I can list data for one username by using


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

But no idea how to add the today and MTD together


Solution

  • 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