4 ways to select Unique items in PowerShell
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
- Using Select-Object Cmdlet
This is probably already your favorite way to find unique items in PowerShell
- Using Get-Unique Cmdlet
The catch with this cmdlet is – it only works with sorted objects by comparing adjacent items.
- 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.
- 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
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.
If you like this article read more similar articles under ‘N – Ways to’ category
- 4 ways to send output to NULL in PowerShell
- 3 ways to store and display PowerShell Variable simultaneously