How Large Are My Folders?

by Oct 21, 2011

To find out the total size of all subfolders in a directory, try this function:

function Get-FolderSize($Path=$home) {
  $code = { ('{0:0.0} MB' -f ($this/1MB)) }
  Get-ChildItem -Path $Path |
    Where-Object { $_.Length -eq $null } |
    ForEach-Object {
      Write-Progress -Activity 'Calculating Total Size for:' -Status $_.FullName
      $sum = Get-ChildItem $_.FullName -Recurse -ErrorAction SilentlyContinue |
        Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue
      $bytes = $sum.Sum
      if ($bytes -eq $null) { $bytes = 0   }
      $result = 1 | Select-Object -Property Path, TotalSize
      $result.Path = $_.FullName
      $result.TotalSize = $bytes | 
        Add-Member -MemberType ScriptMethod -Name toString -Value $code -Force -PassThru    
      $result
    }
}

And this is what a result would typically look like:

PS> Get-FolderSize $env:windir

Path                                                                  TotalSize
----                                                                  ---------
C:\Windows\AABBCC                                                        0,0 MB
C:\Windows\addins                                                        0,0 MB
C:\Windows\AppCompat                                                     3,3 MB
C:\Windows\AppPatch                                                     10,8 MB
C:\Windows\assembly                                                   1972,1 MB
C:\Windows\Boot                                                         27,7 MB
(...)

Twitter This Tip!
ReTweet this Tip!