sortingpowershellformattingexchange-server-2007

Powershell format-table or select-object only show top results


I am trying to find users that have been sending the most emails. But in the end I only want to display the top 10 (or n number) of senders. Is there a way to only show the top results using select-object or format-table

$Messages = Get-ExchangeServer * | where{$_.ServerRole -eq "HubTransport"} | %{get-messagetrackinglog -server $_.name -EventID "SEND" -Start (get-date -format G).AddDays(-1) -ResultSize unlimited}) 2>&1 | out-null

$messages | where{$_.sender -like "*@OurDomain.com*"} | select sender | group sender | sort count -Descending | ft count,name

Is there a way to make this only display the top results?

The only way I can think of would be storing them in a variable and outputting them in a for loop


Solution

  • Before the ft, add:

    select -first 10
    

    Replacing the 10 with how many you want.

    So the full command would be:

    $messages | where{$_.sender -like "*@OurDomain.com*"} | select sender | group sender | sort count -Descending | select -first 10 | ft count,name