Often you may want to count the number of items in each group in an object in PowerShell.
You can use the following syntax to do so:
$my_data | Group-Object team | Select-Object Name, Count
This particular example returns the count of items in each group of the object named $my_data, which has been grouped by the team property.
Here is what the various commands do:
- Group-Object team: Group the rows in the $my_data object based on the team property.
- Select-Object: Specifies that only the group name (in this case the team value) and count should be returned.
The following example shows how to use this syntax in practice.
Example: How to Count Items by Group in PowerShell
Suppose that we have a file named nba_data.csv that contains information about various basketball players.
We can use the following syntax to import this CSV file into an object named $my_data:
$my_data = Import-Csv nba_data.csv
The following screenshot shows how to use this syntax in practice:

Suppose that we would like to count the number of rows for each unique value in the team column.
We can use the following syntax to do so:
$my_data | Group-Object team | Select-Object Name, Count
The following screenshot shows how to use this syntax in practice:

Notice that this returns the name of each unique value from the team column along with the count of each team.
Note: You can find the complete documentation for the Group-Object cmdlet in PowerShell here.
Related Tutorials
The following tutorials explain how to perform other common tasks in PowerShell:
PowerShell: How to Check if Object has Specific Property
PowerShell: How to List All Object Properties
PowerShell: How to Use Group-Object with Multiple Properties
PowerShell: How to Use Sort-Object with Multiple Properties
