Prof. Powershell

Get-Unique -- Same But Different

I still prefer the Select-Object cmdlet, but Get-Unique has a way of weeding out the dupes that's, well, different.

Last time I showed you how to get unique properties using Select-Object. Another tool for getting unique items is the Get-Unique cmdlet. It is possible to use this cmdlet to get the same information we got last time, but in a slightly more complicated fashion. Try this:

PS C:\> get-wmiobject win32_service | select startname | sort startname | get-unique -AsString

While this works, it is not as efficient as using Select-Object, and it's not something I would use for returning unique properties. Get-Unique is really designed to return unique objects from a collection. Here's a very simple illustration:

PS C:\> 6,1,3,3,2,5,5,5,5,6 | sort | get-unique

The array of integers is sorted (you should sort objects before you pipe them to Get-Unique for best results) and then piped to Get-Unique. Here's another example. It's not uncommon to have multiple processes with the same name and this expression weeds out the duplicates:

PS C:\> get-process | sort-object | select processname | get-unique -AsString

This will return a unique list of process names. The AsString parameter instructs Get-Unique to treat the incoming the data as string. The cmdlet's default behavior is to treat incoming data as an object as I showed in the earlier example. You can explicitly tell Get-Unique to treat data as an object using the OnType parameter:

PS C:\> 1,"a","b",3,4.5 | sort | get-unique -ontype

I've piped an array with a few different types of objects, sorted them and then used Get-Unique to return unique objects based on type.

Most cmdlets return objects of the same type so often Get-Unique isn't very useful. But if you have an array you've created with a variety of different object types, as I did in my last example, then Get-Unique can weed out the duplicate objects.

About the Author

Jeffery Hicks is an IT veteran with over 25 years of experience, much of it spent as an IT infrastructure consultant specializing in Microsoft server technologies with an emphasis in automation and efficiency. He is a multi-year recipient of the Microsoft MVP Award in Windows PowerShell. He works today as an independent author, trainer and consultant. Jeff has written for numerous online sites and print publications, is a contributing editor at, and a frequent speaker at technology conferences and user groups.

comments powered by Disqus
Most   Popular