PowerShell supports different features to work with a collection of objects, such as List, Array, and Hashtable. In this post, we will explore how to get distinct items from a collection and find unique objects from a collection of objects by any one of the object properties.
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 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
Find Unique Objects from Array of Objects by Property
In real-time application requirements, we will work with custom PowerShell object array (complex object) instead of a simple string or integer array. The Unique switched parameter can also be used to find distinct objects by a property in a custom object array.
# Initialize the array
$Array = @()
$Array += [PSCustomObject]@{ Name = "User1"; }
$Array += [PSCustomObject]@{ Name = "User2"; }
$Array += [PSCustomObject]@{ Name = "User2"; }
$Array += [PSCustomObject]@{ Name = "User3"; }
$ResultArray = $Array | Select-Object -Unique -Property Name
$ResultArray # Result array with unique Name values
Name
----
User1
User2
User3
As already explained, the Unique parameter with Select-Object cmdlet finds unique values with case-sensitive string comparison. If you work with a string property and want to perform case-insensitive string comparison to find distinct objects, then we need to use the Unique parameter with Sort-Object cmdlet to perform case-insensitive check.
# Initialize the array
$Array = @()
$Array += [PSCustomObject]@{ Name = "User1"; }
$Array += [PSCustomObject]@{ Name = "user2"; }
$Array += [PSCustomObject]@{ Name = "User2"; }
$Array += [PSCustomObject]@{ Name = "User3"; }
# Find unique objects by case-sensitive comparison.
$Array | Select-Object -Unique -Property Name
Name
----
User1
user2
User2
User3
# Find unique objects by case-insensitive comparison.
$Array | Sort-Object -Unique -Property Name
Name
----
User1
User2
User3