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 subdirectories. Also I'd like to be able to sort it by size, optionally.
The du command is a standard Linux/Unix command that allows a user to gain disk usage information quickly. It is best applied to specific directories and allows many variations for customizing the output to meet your needs. As with most commands, the user can take advantage of many options or flags.
Du (disk usage) reports the disk space usage for the directory you specify. By default it recurses directories to show the total size of a directory and its subdirectories.
You can use the Get-ChildItem ( gci alias) and Measure-Object ( measure alias) cmdlets to get the sizes of files and folders (including subfolders) in PowerShell.
Du.exe is a command-line tool that reports the disk space usage of a directory you specify, and by default, the sub-directories.
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
I modified the command in the answer slightly to sort descending by size and include size in 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
Output:
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
Maybe it is not the most efficient method, but it works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With