tags:

views:

43

answers:

3

How can I list size of each folder in a directory by the sum of all files in each folder/subfolders?

My latest attempt:

ls | foreach-object { select-object Name, @{Name = "Size"; Expression = { ls $_ -recurse | measure-object -property length -sum } }

I've made other attempts but nothing successful yet. Any suggestions or solutions are very welcome. I feel like I'm missing something very obvious.

The output should look as follows:

Name Size

And it should list each folder in the root folder and the size of the folder counting subfolders of that folder.

I was able to resolve the issue with the following:

param([String]$path)
ls $path | Add-Member -Force -Passthru -Type ScriptProperty -Name Size -Value {  
   ls $path\$this -recurse | Measure -Sum Length | Select-Object -Expand Sum } | 
   Select-Object Name, @{Name = "Size(MB)"; Expression = {"{0:N0}" -f ($_.Size / 1Mb)} } | sort "Size(MB)" -descending
A: 

Here is a handy Powershell example script that may be adapted to fit what you are looking for.

RandomNoob
I was looking for something more simplistic and a one-liner if possible. I am well aware of how to do it without piping the data.
Jered Odegard
A: 

It's not particularly elegant but should get the job done:

gci . -force | ?{$_.PSIsContainer} | 
   %{$res=@{};$res.Name=$_.Name; $res.Size = (gci $_ -r | ?{!$_.PSIsContainer} |
     measure Length -sum).Sum; new-object psobject -prop $res}

Note the use of -Force to make sure you're summing up hidden files. Also note the aliases I have used (convenient when typing interactively). There's ? for Where-Object and % for Foreach-Object. Saves the wrists. :-)

Keith Hill
Brilliant. You create a blank object and append it attributes? Your case is the $res variable.
Jered Odegard
Yeah, one of the little new features in PowerShell 2.0 is that you can specify a hashtable to the -Property parameter of New-Object. For most types you create, this would set existing properties that match up to keys in the hashtable to the corresponding hashtable value. However if the type is psobject, then new-object will *create* those properties for you and set their values from the hashtable.
Keith Hill
Very nice. I have a lot more control knowing this.
Jered Odegard
+1  A: 

I think you've basically got it, honestly.

You could be a bit more elegant by using Add-Member:

ls | Add-Member -Force -Passthru -Type ScriptProperty -Name Length -Value { 
   ls $this -recurse | Measure -Sum Length | Select -Expand Sum }

PSCX messes with the formatting and will output "" for the size even though you've actually got a size. If you're using PSCX you'll have to add an explicit | Format-Table Mode, LastWriteTime, Length, Name -Auto

Jaykul