PowerShell: How to Count Occurrences of Each Element in Array


Often you may want to count the number of occurrences of each element in an array in PowerShell.

You can use the following syntax to do so:

$my_array | Group

This particular example will return the count of occurrences of each unique value in the array named $my_array.

You can also use the following syntax to return the count of occurrences, sorted in descending order by count:

$my_array | Group | Sort Count -Descending | Select Name, Count

The following example shows how to use each of these methods in practice.

Example: How to Count Occurrences of Each Element in Array in PowerShell

Suppose that we create the following array in PowerShell named $my_array:

$my_array = @(1, 1, 1, 4, 5, 5, 8, 8, 8, 9, 12)

We can use the following syntax to count the number of occurrences of each unique value in the array:

$my_array | Group

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

Notice that this returns an object with the following properties:

  • Count: The count of occurrences of the element
  • Name: The element name
  • Group: A group that contains each occurrence of the element

We could also use the following syntax to return the count of occurrences of each element sorted in descending order:

$my_array | Group | Sort Count -Descending | Select Name, Count

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

PowerShell count occurrences of each element in array

From the output we can see:

  • The value 8 occurs 3 times in the array.
  • The value 1 occurs 3 times in the array.
  • The value 5 occurs 2 times in the array.

And so on.

Feel free to leave out the parameter -Descending if you would instead like to display the count of occurrences in ascending order.

Related Tutorials

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

PowerShell: How to Calculate the Average of an Array
PowerShell: How to Find Minimum and Maximum Values in Array
PowerShell: How to Compare Two Arrays
PowerShell: How to Find Duplicate Values in Array

Leave a Reply