tags:

views:

28

answers:

2

I have a variable results ($result) of several rows of data or object like this:

PS> $result | ft -auto;
name   value
----   -----
a          1
a          2
b          30
b          20
....

what I need to get all the rows of name and max(value) like this filtered output:

PS> $result | ? |ft -auto
name   value
----   -----
a          2
b          30
....

Not sure what command or filters available (as ? in above) so that I can get each name and only the max value for the name out?

+1  A: 

This should do the trick:

PS> $result | Foreach {$ht=@{}} `
                      {if ($_.Value -gt $ht[$_.name].Value) {$ht[$_.Name]=$_}} `
                      {$ht.Values}

This is essentially using the Begin/Process/End scriptblock parameters of the Foreach-Object cmdlet to stash input objects with a max value based on a key into a hashtable.

Note: watch out for extra spaces after the line continuation character (`) - there shouldn't be any.

Keith Hill
nice solution for the case in my Q by using hash-table. My Q is actually a simplified one. Not sure if this S would apply to the case with additional columns (name, value, tag, ...).
David.Chu.ca
It depends. If you can "key" off a single column name for testing for a max value then it should work fine. Keep in mind that the hashtable stores the original object so all the fields are preserved.
Keith Hill
A: 

$result | group name | select name,@{n='value';e={ ($_.group | measure value -max).maximum}}

Shay Levy