在Powershell中显示大小的目录结构

ira*_*hil 5 directory size powershell

尝试使用"dir"命令显示子文件夹和文件的大小.在谷歌搜索"powershell目录大小"后,我找到了两个有用的链接

  1. 确定文件夹的大小 http://technet.microsoft.com/en-us/library/ff730945.aspx
  2. PowerShell脚本获取目录总大小的PowerShell脚本以获取目录总大小

这些灵魂很棒,但我正在寻找类似"dir"输出的东西,方便而简单,我可以在文件夹结构中的任何地方使用.

所以,我最终做了这个,任何建议,使它简单,优雅,高效.

Get-ChildItem | 
Format-Table  -AutoSize Mode, LastWriteTime, Name,
     @{ Label="Length"; alignment="Left";
       Expression={ 
                    if($_.PSIsContainer -eq $True) 
                        {(New-Object -com  Scripting.FileSystemObject).GetFolder( $_.FullName).Size}  
                    else 
                        {$_.Length} 
                  }
     };  
Run Code Online (Sandbox Code Playgroud)

谢谢.

Kei*_*ill 8

第一个小mod是为了避免为每个目录创建一个新的FileSystemObject.使其成为一个函数并将新对象拉出管道.

function DirWithSize($path=$pwd)
{
    $fso = New-Object -com  Scripting.FileSystemObject
    Get-ChildItem | Format-Table  -AutoSize Mode, LastWriteTime, Name, 
                    @{ Label="Length"; alignment="Left"; Expression={  
                         if($_.PSIsContainer)  
                             {$fso.GetFolder( $_.FullName).Size}   
                         else  
                             {$_.Length}  
                         } 
                     }
}
Run Code Online (Sandbox Code Playgroud)

如果你想完全避免使用COM,你可以使用PowerShell计算dir大小,如下所示:

function DirWithSize($path=$pwd)
{
    Get-ChildItem $path | 
        Foreach {if (!$_.PSIsContainer) {$_} `
                 else {
                     $size=0; `
                     Get-ChildItem $_ -r | Foreach {$size += $_.Length}; `
                     Add-Member NoteProperty Length $size -Inp $_ -PassThru `
                 }} |
        Format-Table Mode, LastWriteTime, Name, Length -Auto
}
Run Code Online (Sandbox Code Playgroud)