PowerShell: How to Use Group-Object with Multiple Properties


Often you may want to use the Group-Object cmdlet in PowerShell to group by multiple properties and then perform some calculation.

You can use the following syntax to do so:

Import-Csv $my_file |
Group-Object -Property Team,Position |
% {$b=$_.name -split ', ';$c=($_.group |
Measure-Object -Property Points -Sum).Sum;
[PScustomobject]@{Team=$b[0];Position=$b[1];Sum=$c}}

This particular example does the following:

  • Imports the CSV file specified at the path in the $my_file variable.
  • Groups by the values in the Team and Position columns.
  • Calculates the sum of the Points column, grouped by Team and Position.
  • Outputs the results in a table using a PScustomobject.

The following example shows how to use this syntax in practice.

Example: How to Use Group-Object with Multiple Properties in PowerShell

Suppose we have a CSV file saved at the following location:

  • c:\users\bobbi\player_data.csv

Suppose we use the Import-Csv cmdlet to view the contents of this entire file:

The file contains three columns that show the Team, Position and Points scored by various basketball players.

Suppose that we would like to group the rows based on values in the Team and Position columns, then calculate the sum of values in the Points column.

We can use the following syntax to do so:

Import-Csv $my_file |
Group-Object -Property Team,Position |
% {$b=$_.name -split ', ';$c=($_.group |
Measure-Object -Property Points -Sum).Sum;
[PScustomobject]@{Team=$b[0];Position=$b[1];Sum=$c}}

The following screenshot shows how to use this syntax in practice:

PowerShell Group-Object multiple properties

The output displays the sum of the values in the Points column, grouped by the values in the Team and Position columns.

From the output we can see:

  • The sum of points for the Mavs Guards is 36.
  • The sum of points for the Mavs Forwards is 42.
  • The sum of points for the Spurs Guards is 24.
  • The sum of points for the Spurs Forwards is 25.

Note that in this example we grouped by two properties, but you can use similar syntax to group by as many properties as you would like.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Replace Every Occurrence of String in File
PowerShell: How to Replace Text with Wildcard
PowerShell: How to Replace Special Characters in String

Leave a Reply