You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对PowerShell服务器磁盘空间报告中的Percent字段进行升序或降序排序?

如何对PowerShell服务器磁盘空间报告中的Percent字段进行升序或降序排序?

没问题!你遇到的核心问题是当前脚本里的Percent字段是格式化后的字符串(比如95,00%),直接用Sort-Object排序的话会按字符顺序来,而不是我们想要的数值大小排序。下面给你两种可行的解决方案:

方法一:新增数值字段用于排序(推荐)

这种方法会在计算时额外生成一个纯数值的PercentValue字段,专门用来排序,最后输出时只显示格式化后的Percent,逻辑更清晰,也避免了字符串转数值的潜在问题:

# 先初始化结果数组,避免未定义的报错
$DiskSizeReport = @()

$computers | ForEach {
    $Disks = Get-WMIObject Win32_Logicaldisk -ComputerName $_ -Filter "Drivetype=3" -Credential $cred -ErrorAction SilentlyContinue |
        Select PSComputername,
               DeviceID,
               @{Name="Size GB";Expression={$_.Size/1GB -as [int]}},
               @{Name="Used";Expression={ (($_.Size/1GB -as [int]) - ($_.Freespace/1GB -as [int])) }},
               @{Name="Free";Expression={($_.Freespace/1GB -as [int])}},
               # 新增数值型的PercentValue,用于排序(保留两位小数的数值)
               @{Name="PercentValue";Expression={[math]::Round((($_.Freespace/1GB -as [int]) / ($_.Size/1GB -as [int]) ),2)}},
               # 原有的格式化百分比字符串,用于最终显示
               @{Name="Percent";Expression={[math]::Round((($_.Freespace/1GB -as [int]) / ($_.Size/1GB -as [int]) ),2).toString("P") }}

    $DiskSizeReport += $Disks
}

# 按PercentValue降序排序,最后选择需要显示的字段(排除PercentValue)
$DiskSizeReport | Sort-Object -Property PercentValue -Descending | Select PSComputername, DeviceID, 'Size GB','Used','Free','Percent'

# 如果需要升序排序,只需要把-Descending改成-Ascending即可

方法二:排序时直接转换字符串为数值

如果不想新增字段,也可以在排序阶段把Percent字符串转换为数值,需要注意处理掉百分号和逗号(因为你的格式是95,00%,逗号是小数点分隔符):

$DiskSizeReport = @()

$computers | ForEach {
    $Disks = Get-WMIObject Win32_Logicaldisk -ComputerName $_ -Filter "Drivetype=3" -Credential $cred -ErrorAction SilentlyContinue |
        Select PSComputername,
               DeviceID,
               @{Name="Size GB";Expression={$_.Size/1GB -as [int]}},
               @{Name="Used";Expression={ (($_.Size/1GB -as [int]) - ($_.Freespace/1GB -as [int])) }},
               @{Name="Free";Expression={($_.Freespace/1GB -as [int])}},
               @{Name="Percent";Expression={[math]::Round((($_.Freespace/1GB -as [int]) / ($_.Size/1GB -as [int]) ),2).toString("P") }}

    $DiskSizeReport += $Disks
}

# 排序时将Percent字符串转为小数:去掉%,替换逗号为点,再转成数值类型
$DiskSizeReport | Sort-Object -Property @{Expression={[double]$_.Percent.Replace('%','').Replace(',','.')}} -Descending | Select PSComputername, DeviceID, 'Size GB','Used','Free','Percent'

额外提示:原脚本里最好先初始化$DiskSizeReport = @(),避免第一次运行时因为变量未定义出现错误哦~

备注:内容来源于stack exchange,提问作者Bra Tabs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.23 15:37:59