Sort-Object by greatest numerical value value from

2019-02-27 08:06发布

问题:

I want the greatest value (mailboxSize) at the top of the file. I have a cvs as inport.

When I do the following sort cmd:

Import-Csv import.csv| Sort-Object MailboxSize,DisplayName -Descending | Export-Csv SORT.csv

I get the following result:

"DisplayName","MailboxSize"

"persone6","9941"
"persone3","8484"
"persone1","7008"
"persone4","4322"
"persone5","3106"
"persone7","27536"
"persone10","24253"
"persone8","1961"
"persone9","17076"
"persone11","17012"
"persone2","15351"
"persone12","11795"
"persone14","1156"
"persone13","1008"

But I want this as a result!

"persone7","27536"
"persone10","24253"
"persone9","17076"
"persone11","17012"
"persone2","15351"
"persone12","11795"
"persone6","9941"
"persone3","8484"
"persone1","7008"
"persone4","4322"
"persone5","3106"
"persone14","1156"
"persone13","1008"

回答1:

When importing a CSV-file, all properties are made string-type. You have to cast the MailboxSize to an int before you can sort it properly. Try:

Import-Csv import.csv |
Sort-Object {[int]$_.MailboxSize}, DisplayName -Descending |
Export-Csv SORT.csv

You should also use the -NoTypeInformation switch in Export-CSV to avoid the #TYPE ..... line (first line in an exported CSV-file).

Sample:

$data = @"
    "DisplayName","MailboxSize"   
    "persone6","9941"
    "persone3","8484"
    "persone1","7008"
    "persone4","4322"
    "persone5","3106"
    "persone7","27536"
    "persone10","24253"
    "persone8","1961"
    "persone9","17076"
    "persone11","17012"
    "persone2","15351"
    "persone12","11795"
    "persone14","1156"
    "persone13","1008"
"@ | ConvertFrom-Csv

$data |
Sort-Object {[int]$_.MailboxSize}, DisplayName -Descending |
Export-Csv SORT.csv -NoTypeInformation

SORT.csv

"DisplayName","MailboxSize"
"persone7","27536"
"persone10","24253"
"persone9","17076"
"persone11","17012"
"persone2","15351"
"persone12","11795"
"persone6","9941"
"persone3","8484"
"persone1","7008"
"persone4","4322"
"persone5","3106"
"persone8","1961"
"persone14","1156"
"persone13","1008"

I'm guessing the usernames are fake, but be aware that the same issue goes for DisplayName if your usernames actually was personeXX where XX is an int. Like:

persone7     27536
persone20    27536
persone13    27536

To sort them probably, you'd have to create a scriptblock for Sort-Object or create your own function to split the value and sort them correctly.