gpt4 book ai didi

powershell - 按 Import-CSV 中的最大数值对对象进行排序

转载 作者:行者123 更新时间:2023-12-02 18:50:02 25 4
gpt4 key购买 nike

我想要文件顶部的最大值 (mailboxSize)。我有一个 cvs 作为输入。

当我执行以下排序命令时:

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"
<小时/>

但我想要这个结果!

"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 文件时,所有属性均设为字符串类型。您必须将 MailboxSize 转换为 int 才能正确排序。尝试:

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

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

示例:

$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

排序.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 也会出现同样的问题。喜欢:

persone7     27536
persone20 27536
persone13 27536

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

关于powershell - 按 Import-CSV 中的最大数值对对象进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27827398/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com