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

如何在PowerShell中基于自定义对象Size对文件夹大小输出排序?

获取文件夹大小并按Size属性排序的PowerShell解决方案

你目前的PowerShell函数可以获取指定目录下各子文件夹的大小,但输出未按Size属性排序。以下是两种实现排序的方法:

原函数代码

function Get-FolderSize {
      [CmdletBinding()]
      param (
        [Parameter(ValueFromPipeline=$true)]
        [string]$Path
      )
      
      process {
        $folders = Get-ChildItem $Path -Directory
        foreach ($folder in $folders) {
          $size = [Math]::round((Get-ChildItem $folder.FullName -Recurse | Measure-Object -Property Length -Sum).Sum / 1GB, 2)
          $obj = New-Object PSObject -Property @{
            Name = $folder.Name
            Size = $size
          }
          $obj
        }
      }
    };
    $path =  pwd;
    Get-FolderSize -Path $path -ErrorAction SilentlyContinue;

方法一:调用时通过管道排序(灵活调整排序方向)

直接在函数输出后添加Sort-Object命令,可按需指定升序(-Ascending)或降序(-Descending):

$path = pwd;
Get-FolderSize -Path $path -ErrorAction SilentlyContinue | Sort-Object -Property Size -Descending

这种方式无需修改函数本身,适合临时调整排序规则的场景。

方法二:修改函数默认输出排序

如果希望函数默认返回排序后的结果,可以修改函数逻辑,先收集所有结果再排序输出,同时推荐使用更简洁的[PSCustomObject]创建自定义对象:

function Get-FolderSize {
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline=$true)]
        [string]$Path
    )
    
    process {
        $folders = Get-ChildItem $Path -Directory
        # 收集所有文件夹大小结果
        $sizeResults = foreach ($folder in $folders) {
            $size = [Math]::round((Get-ChildItem $folder.FullName -Recurse | Measure-Object -Property Length -Sum).Sum / 1GB, 2)
            [PSCustomObject]@{
                Name = $folder.Name
                Size = $size
            }
        }
        # 按Size属性降序输出,可改为-Ascending实现升序
        $sizeResults | Sort-Object -Property Size -Descending
    }
};
$path = pwd;
Get-FolderSize -Path $path -ErrorAction SilentlyContinue;

排序后示例输出

按降序排序后的结果如下:

Name                 Size
----                 ----
Downloads            1.66
eclipse              0.29
eclipse-workspace    0.16
workspace            0.16
git                  0.12
Documents            0.09
iotedge              0.04
getting-started      0.01
Favorites               0
Desktop                 0
Links                   0
source                  0
Searches                0

内容的提问来源于stack exchange,提问作者Bharath G Kumar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 00:10:13