jamiet jamiet - 3 months ago 12
PowerShell Question

Understanding uniqueness in arrays of hashtables

Take this code, with output:

> (@(@{"number"=1},@{"number"=1},@{"number"=2})).Count
3
> (@(@{"number"=1},@{"number"=1},@{"number"=2}) | select -uniq).Count
1


I was expecting the second statement to return
2
. Clearly it doesn't but I don't understand the rationale for why not. Why does the
-uniq
option consider all of these three hashtables to be the same?

A follow on question, I want to remove duplicates from this:

@(@{"number"=1},@{"number"=1},@{"number"=2})


in order that the result is

@(@{"number"=1},@{"number"=2})


How do I do that?

Answer

Use Sort-Object -Unique instead of Select-Object -Unique if you want to evaluate the uniqueness of values but have the entire hashtable returned:

@(@{"number"=1},@{"number"=1},@{"number"=2}) | Sort-Object Values -Unique