PowerShell by Patrik

Get Unique Objects from Array of Objects by Property in PowerShell

In real-time application requirements, we will work with a 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 a case-insensitive string comparison to find distinct objects, then we need to use the Unique parameter with Sort-Object cmdlet to perform a 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
PowerShell
Distinct
Unique

Comments