'Powershell make list with object groupping

Assuming a CSV File:

Name,group_name,group_id
foo,Best,1
bar,Worst,2
baz,Best,1
bob,Worst,2

What's the simplest form of Grouping by Powershell I can use to have output like:

Count    group_id    group_name Names
-----    --------    ---------- -----
2        1           Best       ["foo", "baz"]
2        2           Worst      ["bar", "bob"]


Solution 1:[1]

Use the Group-Object cmdlet to group the rows together by name and id, then use Select-Object to extract the appropriate details from each group as individual properties:

# replace with `$Data = Import-Csv path\to\file.csv`
$Data = @'
Name,group_name,group_id
foo,Best,1
bar,Worst,2
baz,Best,1
bob,Worst,2
'@|ConvertFrom-Csv

# Group rows, then construct output record with `Select-Object`
$Data |Group-Object group_name,group_id |Select-Object Count,@{Name='group_id';Expression={$_.Group[0].group_id}},@{Name='group_name';Expression={$_.Group[0].group_name}},@{Name='Names';Expression={$_.Group.Name}}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mathias R. Jessen