views:

375

answers:

2
+1  Q: 

du in powershell?

How can I get a "du" -ish analysis using powershell? I'd like to periodically check the size of directories on my disk.

The following gives me the size of each file in the current directory:

foreach ($o in gci)
{
   Write-output $o.Length
}

But what I really want is the aggregate size of all files in the directory, including subdirs. Also I'd like to be able to sort it by size, optionally.

EDIT: some additional context. I'm a dev, but I admin my dev machines.

+6  A: 

There is an implementation available at the "Exploring Beautiful Languages" blog:

"An implementation of 'du -s *' in Powershell"

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

(Code by the blog owner: Luis Diego Fallas)

Output:

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
Tomalak
cool! I am in awe of Luis' powershell fu. according to powershell conventions, shouldn't the name of functions be verb-object ? So... summarize-directory or something, instead of directory-summary ?
Cheeso
Ask him. I'm just quoting him. :) But I think that was the convention.
Tomalak
+4  A: 

When you use Get-ChildItem make sure you use the -Force parameter or you won't get hidden and system files. And these files can definitely contribute to your dir size.

Keith Hill