Successfully added
PowerShell Array Guide
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
Referenced in:
Leave a Comment
All fields are required. Your email address will not be published.
Comments(4)
KennethDap
9/6/2023 1:57:08 AMVikcomres
9/5/2023 2:24:43 PMZasvenufep
9/3/2023 4:00:39 AMAvromanfep
9/2/2023 1:13:27 PM