开发者

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-o开发者_StackOverflow社区bject 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


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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜