Sort-Object by greatest numerical value value from Import-CSV

房东的猫 提交于 2019-12-02 01:46:14

问题


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.



来源:https://stackoverflow.com/questions/27827398/sort-object-by-greatest-numerical-value-value-from-import-csv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!