Author Posts

October 20, 2016 at 3:09 pm

Hello guys,

I'm looking for a PowerShell one liner doing the same as "sort | uniq -c | sort -nr" on a Unix shell.

Using for example

@(55,22,33,44,11,44,33,22,11,33,22,11,22,11,11) | group-object | format-table -h count,name

will deliver

1 55
4 22
3 33
2 44
5 11

But the goal is to have this list sorted by frequency in descending order.

Trying

@(55,22,33,44,11,44,33,22,11,33,22,11,22,11,11) | group-object | format-table -h count,name | sort-object -descending

doesn't work.

Using a temporary file will do the job but this is not an elegant solution.

@(55,22,33,44,11,44,33,22,11,33,22,11,22,11,11) | group-object | format-table -h count,name >tmp
get-content tmp | sort-object -descending

5 11
4 22
3 33
2 44
1 55

Anybody to propose a clean and straightforward way to execute such task in PowerShell just like in the Unix shell?

October 20, 2016 at 3:33 pm

Hi Horst

The problem is with your use of the Format-Table commandlet. PowerShell send objects through the pipeline, and all cmdlets are made to work with objects rather than text. But as soon as you use one of the 'Format-' cmdlets, you no longer have true objects, and the other cmdlets can't work with that output.

Your problem could be solved with this one-liner:

@(55,22,33,44,11,44,33,22,11,33,22,11,22,11,11) | Group-Object | Select-Object -Property Count, Name | Sort-Object -Property Count -Descending

Or if you want it shorter, you can do it with aliases instead:

@(55,22,33,44,11,44,33,22,11,33,22,11,22,11,11) | group | select Count, Name | sort Count -d

/Christian

October 20, 2016 at 3:57 pm

Hello Christian,

very cool.
This is it.

Thanks,
Horst

October 20, 2016 at 5:09 pm

Some of us frequent both sapien and powershell.org forums. Be patient for an answer=D

October 21, 2016 at 3:47 pm

Some of us frequent both sapien and powershell.org forums. Be patient for an answer=D

Sorry 'bout that, chief.
Had some trouble to register here...