Get Unique Items from Array in PowerShell

We can use the Unique switched parameter from Select-Object or Sort-Object cmdlet to remove duplicate items and get only distinct items from an array.

$Array = @('one', 'two','three','three','four','five')
$Result = $Array | Select-Object -Unique
$Result  #List only unique items 

The Unique parameter with the Select-Object cmdlet performs case-sensitive string comparison, so we need to use it with the Sort-Object cmdlet to perform a case-insensitive check.

$Array = @('one', 'two','three','Three','four')
 
#Remove duplicates by case-sensitive check.
$Array | Select-Object -Unique
 
#Output – one, two, three, Three, four
 
#Remove duplicates by case-insensitive check.
$Array | Sort-Object -Unique
 
#Output - four, one, three, two
PowerShell
Distinct
Unique

Comments

Leave a Comment

All fields are required. Your email address will not be published.