Get-Unique

PowerShell Cmdlet Deep Dive: Get-Unique

Welcome back to Wahmans PowerShell Blog! Today, we’re diving into a PowerShell cmdlet that is simple yet powerful when working with lists of items: Get-Unique. This cmdlet helps you return unique items, but there’s a catch – it only works properly on a sorted list.

As per Microsoft’s documentation:

Get-Unique: Returns unique items from a sorted list.

This means that if you want accurate results, you need to make sure your data is sorted first. Now, let’s go through some examples from beginner to more advanced usage.

🧰 Example 1: Basic Usage with Strings

"apple", "banana", "apple", "orange" | Sort-Object | Get-Unique

Output:

apple
banana
orange

Here, we’re piping a list of strings to Sort-Object first, then Get-Unique gives us a list without duplicates.

🧰 Example 2: Working with Numbers

10, 2, 5, 10, 2, 7 | Sort-Object | Get-Unique

Output:

2
5
7
10

Simple numeric deduplication – remember to always sort first!

🧰 Example 3: Filtering Unique Event Log Sources

Get-EventLog -LogName System -Newest 1000 |
    Select-Object -ExpandProperty Source |
    Sort-Object |
    Get-Unique

This example pulls the latest 1000 system events, extracts the Source field, sorts it, and then lists only unique sources. Very handy when investigating system logs.

🧰 Example 4: Advanced – Comparing Two Sorted Lists

$list1 = "blue", "green", "red", "yellow"
$list2 = "green", "red", "purple"

($list1 + $list2) |
    Sort-Object |
    Get-Unique

Output (depending on input):

blue
green
purple
red
yellow

Although this returns all unique items from both lists, Get-Unique only gets rid of immediate duplicates. If you’re looking for a true unique compare operation, consider using Compare-Object or Select-Object -Unique for more complex needs.

⚠️ A Word of Caution

Get-Unique removes adjacent duplicates only. Always sort your input if you want reliable deduplication.

🧠 Bonus Tip

# Incorrect usage - not sorted
echo "b", "a", "b" | Get-Unique
# Output: b, a, b

# Correct usage
echo "b", "a", "b" | Sort-Object | Get-Unique
# Output: a, b

And there you have it, folks – a simple yet essential cmdlet that you’ll find yourself using more often than you think when working with lists, logs, and data streams!

Happy scripting, and I will see you in the next post!

Leave a Reply

Your email address will not be published. Required fields are marked *