在PowerShell中?

Che*_*eso 24 windows powershell diskspace

我怎样才能得到一个使用PowerShell的-ish分析?我想定期检查磁盘上目录的大小.

以下给出了当前目录中每个文件的大小:

foreach ($o in gci)
{
   Write-output $o.Length
}
Run Code Online (Sandbox Code Playgroud)

但我真正想要的是目录中所有文件的聚合大小,包括子目录.此外,我希望能够按大小排序,可选.

Tom*_*lak 28

"探索美丽语言"博客中提供了一个实现:

"在Powershell中实现'du -s*'"

function directory-summary($dir=".") { 
  get-childitem $dir | 
    % { $f = $_ ; 
        get-childitem -r $_.FullName | 
           measure-object -property length -sum | 
             select @{Name="Name";Expression={$f}},Sum}
}
Run Code Online (Sandbox Code Playgroud)

(博客所有者代码:Luis Diego Fallas)

输出:

PS C:\Python25> directory-summary

Name                  Sum
----                  ---
DLLs              4794012
Doc               4160038
include            382592
Lib              13752327
libs               948600
tcl               3248808
Tools              547784
LICENSE.txt         13817
NEWS.txt            88573
python.exe          24064
pythonw.exe         24576
README.txt          56691
w9xpopen.exe         4608

  • 它会更像是get-directorysummary(有一个标准的动词列表) (5认同)
  • 凉!我对Luis的powershell fu敬畏.根据powershell约定,函数的名称不应该是动词对象吗?那么...总结一下目录或什么,而不是目录摘要? (2认同)

小智 21

我稍微修改了答案中的命令,按大小排序降序,并以MB为单位包含大小:

gci . | 
  %{$f=$_; gci -r $_.FullName | 
    measure-object -property length -sum |
    select  @{Name="Name"; Expression={$f}}, 
            @{Name="Sum (MB)"; 
            Expression={"{0:N3}" -f ($_.sum / 1MB) }}, Sum } |
  sort Sum -desc |
  format-table -Property Name,"Sum (MB)", Sum -autosize
Run Code Online (Sandbox Code Playgroud)

输出:

PS C:\scripts> du

Name                                 Sum (MB)       Sum
----                                 --------       ---
results                              101.297  106217913
SysinternalsSuite                    56.081    58805079
ALUC                                 25.473    26710018
dir                                  11.812    12385690
dir2                                 3.168      3322298
Run Code Online (Sandbox Code Playgroud)

也许它不是最有效的方法,但它有效.


小智 8

如果您只需要该路径的总大小,可以使用一个简化版本,

Get-ChildItem -Recurse ${HERE_YOUR_PATH} | Measure-Object -Sum Length
Run Code Online (Sandbox Code Playgroud)