4

I typed the following command to find out how many unique objects there were and it gave me 5. I don't know why this gives 5.

> $var = @(2,4,2,5,3,6,34,6,3,6,4,6,3,5,5,353,5343,5,3,56,34)  
>$var | sort -Unique  
2  
3  
4  
5  
6  
34  
56  
353  
5343  
>$var | sort -Unique Count  
5
3
  • Good question! This seems like a bug to me... 5 seems to be coming from the parameter -Property but i'm not sure why. -Property seems to take any string... The number returned is just an item from the incoming list, for example 1,4,6,12,65,3,13 | Sort-Object -Unique -Property itsABugMaybe returns 65. You might want to post this here Commented Feb 18, 2012 at 1:54
  • Thanks I posted it there as you suggested. - connect.microsoft.com/PowerShell/feedback/details/725505/… Commented Feb 18, 2012 at 2:03
  • I'll vote that up too. It's definitely flakey. If you reverse the array, it comes out 34. Commented Feb 18, 2012 at 4:54

2 Answers 2

8

$var | sort -Unique COUNT is the same as: $var | sort -Unique -Property COUNT

So what sort is doing is looking for the "COUNT" property on each of the elements in the array to determine whether they are unique or not. You can see how this works if you do the following:

GPS sv* | sort -Unique ID
GPS sv* | sort -Unique Name

Since none of the objects have a "COUNT" property, sort sees them all as the same and therefore none are unique and it is returning one of the elements. The clue came from trying the following:

$var = $("a", "b", "c", "b")
$var | sort -Unique count

this produced the result "c".

Measure is your friend here:

$var |sort -Unique |measure

That should do the trick.

Sign up to request clarification or add additional context in comments.

1 Comment

"and it is returning one of the elements", so it randomly returns a value in the list? It seems it also returns the same element if you don't add the an element in the list.
3

I'm not sure why it's doing that either, but -sort doesn't have a count parameter.

I think what you might be after is:

$var = @(2,4,2,5,3,6,34,6,3,6,4,6,3,5,5,353,5343,5,3,56,34)  
($var | sort -Unique).count  

2 Comments

The string "Count" is filling in the positional for -Property (Position 1) which is outputting one of the items from the incoming object for some reason.
Well certainly your answer is the right way to do it. I was trying to understand why is going behind the scenes here. Thanks for responding.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.