Powershell: Get Unique Objects in a two column array

Viewed 1043

I have a file with the following columns: RecipientAddress and MessageId

I need to get only conntent with unique RecipientAddress. If I run:

Import-Csv $File_MsgList | select RecipientAddress | Sort-Object RecipientAddress | Get-Unique -AsString

It filters out the duplicates correctly. But If I want to get the associated MessageId as well, it is not able to remove the duplicate addresses anymore.

Import-Csv $File_MsgList | select RecipientAddress, MessageId | Sort-Object RecipientAddress | Get-Unique -AsString

How can I get both columns as well as get uniques on the first column?

1 Answers

That is because Get-Unique filters each unique item (object) including all its properties.
Instead you might simply use the -Unique parameter on the Sort-Object cmdlet:

$MsgList = ConvertFrom-Csv @'
RecipientAddress, MessageId
a@domain.com,1
b@domain.com,2
b@domain.com,3
c@domain.com,4
'@

$MsgList | select RecipientAddress, MessageId | Sort-Object RecipientAddress -unique

RecipientAddress MessageId
---------------- ---------
a@domain.com     1
b@domain.com     2
c@domain.com     4
Related