4 ways to select Unique items in Powershell

Following are the approaches that I could come up with, there may be few more, feel free to point them out and I’ll update the article

  1. Using Select-Object Cmdlet

    This is probably already your favorite way to find unique items in PowerShell

    Unique items in PowerShell

  2. Using Get-Unique Cmdlet

    The catch with this cmdlet is – it only works with sorted objects by comparing adjacent items.

    Unique items in PowerShell

  3. Using [HashSet<T>]

    HashSets are data structures that only hold unique items, you can typecast your array in our exampleto a [HashSet]

    I was not aware that, .Net provides a class for HashSets which I learned a few weeks back and to my wonder, they seem to be better in performance.

    But in case you are worried, typecasting to HashSet will change the data type and you can’t perform methods available like in the data type [Array], then please be aware that you can typecast them back to System.Array , like in the below image.

    Unique items in PowerShell

  4. Using LINQ

    Language-Integrated Query (LINQ) is the name for a set of technologies based on the integration of query capabilities directly into the C# language, and the good news is that it can be used directly in PowerShell

    Unique items in PowerShell

NOTE: The performance varies in all 4 approaches, in the following screenshot you can clearly see the difference, the use of pipeline probably slows down the cmdlets – Select-OBject and Get-Unique.

Unique items in PowerShell

If you like this article read more similar articles under ‘N – Ways to’ category



Subscribe to our mailing list

* indicates required