Jered Odegard
Jered Odegard

Reputation: 223

Listing Folder Size by Piping

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

Upvotes: 2

Views: 5330

Answers (3)

Keith Hill
Keith Hill

Reputation: 201662

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. :-)

Upvotes: 1

Jaykul
Jaykul

Reputation: 15824

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

Upvotes: 5

Ta01
Ta01

Reputation: 31610

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

Upvotes: 0

Related Questions