PowerShell: How to Find Duplicate Values in Array


You can use the following methods in PowerShell to find duplicate values in an array:

Method 1: Find Duplicate Values in Array

$my_array | Group | Where{$_.Count -gt 1} | Select-Object Name

This particular example will return all duplicate values in the array named $my_array.

Method 2: Find Duplicate Values with Count in Array

$my_array | Group | Where{$_.Count -gt 1} | Select-Object Name, Count

This particular example will return all duplicate values along with the number of times each duplicate value occurs in the array named $my_array.

Note: Both methods work by using the Count property to count the number of times each value occurs in the array and then by using Where to filter for only the values that have a count greater than 1.

The following examples show how to use both methods in practice.

Example 1: Find Duplicate Values in Array in PowerShell

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

$my_array = @(1, 3, 3, 3, 3, 3, 7, 7, 8, 12)

We can use the following syntax to find all duplicate values in this array:

$my_array | Group | Where{$_.Count -gt 1} | Select-Object Name

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

PowerShell find duplicate values in array

From the output we can see that there are two values in the array that occur more than once:

  • 3
  • 7

Example 2: Find Duplicate Values with Count in Array in PowerShell

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

$my_array = @(1, 3, 3, 3, 3, 3, 7, 7, 8, 12)

We can use the following syntax to find the duplicate values in the array along with the count of how many times each duplicate value occurs:

$my_array | Group | Where{$_.Count -gt 1} | Select-Object Name, Count

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

PowerShell find duplicate values with counts in array

From the output we can see:

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

By using Select-Object Name, Count we are able to return both the value of the duplicate along with the count of how many times it occurs.

Related Tutorials

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

PowerShell: How to Return Multiple Values from Function
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