Using Group-object to sum more than one column (property)

Welcome Forums General PowerShell Q&A Using Group-object to sum more than one column (property)

This topic contains 1 reply, has 2 voices, and was last updated by

 
Participant
3 months, 2 weeks ago.

  • Author
    Posts
  • #110555

    Participant
    Points: 180
    Rank: Participant

    I have a CSV file as follows:

    "ID","M1","M2","M3"
    "122",10,20,30
    "122",30,0,30
    "210",0,0,10
    "210",10,0,0
    "210",0,10,0
    

    Using Group-object how can I produce
    a new CSV file that looks like:

    "ID","M1","M2","M3"
    "122",40,20,60
    "210",10,10,10
    

    Can Group-object accomplish this?
    Thanking you in advance for any advice
    or tips and hints.

  • #110566

    Participant
    Points: 878
    Helping Hand
    Rank: Major Contributor

    Yup, its possible.

    $Csv = Import-Csv -Path c:\YourCsv.csv
    $Csv | Group-Object -Property id | ForEach-Object -Process {
        [PSCustomObject]@{
          Id = $_.Name
          M1 = ($_.Group.M1|Measure -sum).Sum
          M2 = ($_.Group.M2|Measure -sum).Sum
          M3 = ($_.Group.M3|Measure -sum).Sum
        }
    }
    

    I believe this can be made even more simpler.

The topic ‘Using Group-object to sum more than one column (property)’ is closed to new replies.