CSV按最大数值对对象进行排序

CSV按最大数值对对象进行排序

本文介绍了通过Import-CSV按最大数值对对象进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要在文件顶部具有最大的值(mailboxSize).我的简历有简历.

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

当我执行以下排序cmd时:

When I do the following sort cmd:

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

我得到以下结果:

"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"

推荐答案

导入CSV文件时,所有属性均设为string类型.您必须先将MailboxSize强制转换为int,然后才能对其进行正确排序.试试:

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

您还应该使用Export-CSV中的-NoTypeInformation开关来避免#TYPE .....行(导出的CSV文件中的第一行).

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

示例:

$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"

我猜用户名是假的,但是请注意,如果您的用户名实际上是personeXX,而XX是一个整数,则DisplayName也会遇到同样的问题.喜欢:

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

要对它们进行排序,您必须为Sort-Object创建一个脚本块,或者创建自己的函数以拆分值并对其进行正确排序.

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.

这篇关于通过Import-CSV按最大数值对对象进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 19:08