PowerShell: How to Remove Duplicate Values from Array


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

Method 1: Remove Duplicate Values from Array

$my_array | Select -Unique

This particular example will remove all duplicate values from the array named $my_array.

Method 2: Remove Duplicate Values from Array and Sort Resulting Values

$my_array | Sort -Unique

This particular example will remove all duplicate values from the array named $my_array and sort the resulting unique values.

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

Example 1: Remove Duplicate Values from Array

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

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

We can use the following syntax to remove all duplicate values from this array:

$my_array | Select -Unique

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

PowerShell remove duplicates from array

From the output we can see that all duplicate values have been removed from the array and only the following unique values remain:

  • 1
  • 7
  • 3
  • 8
  • 12

Example 2: Remove Duplicate Values from Array and Sort Resulting Values

Once again, suppose that we create the following array in PowerShell named $my_array:

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

We can use the following syntax to find remove all duplicate values from the array and sort the resulting values from smallest to largest:

$my_array | Sort -Unique

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

PowerShell remove duplicates from array and sort

From the output we can see that all duplicate values have been removed from the array and only the following unique values remain:

  • 1
  • 3
  • 7
  • 8
  • 12

Note that the difference between this example and the previous example is that the unique values are sorted from smallest to largest using this method.

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