hdsouza
hdsouza

Reputation: 355

Powershell: Get Unique Objects in a two column array

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?

Upvotes: 2

Views: 2846

Answers (2)

js2010
js2010

Reputation: 27481

You can sort by two columns and get the unique entries based on each main column entry, which here is "name":

'name,number
joe,1
joe,1
john,1
john,1' | convertfrom-csv | sort-object name,number -unique

name number
---- ------
joe  1
john 1

Upvotes: 1

iRon
iRon

Reputation: 23713

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
[email protected],1
[email protected],2
[email protected],3
[email protected],4
'@

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

RecipientAddress MessageId
---------------- ---------
[email protected]     1
[email protected]     2
[email protected]     4

Upvotes: 2

Related Questions