PoshCode Logo PowerShell Code Repository

Get-DirSize (modification of post by view diff)
embed code: <script type="text/javascript" src="http://PoshCode.org/embed/1185"></script>download | new post

A v2.0 function to recursively get the sizes of all subdirectories under a root path.

  1. function Get-DirSize {
  2. <#
  3. .Synopsis
  4.   Gets a list of directories and sizes.
  5. .Description
  6.   This function recursively walks the directory tree and returns the size of
  7.   each directory found.
  8. .Parameter path
  9.   The path of the root folder to start scanning.
  10. .Example
  11.   # Get the largest folder under the user profile
  12.   PS> (Get-DirSize $env:userprofile | sort Size)[-1]
  13. .Example
  14.   # Get the folder sizes of all folders under each folder in $folders
  15.         PS> $folders | Get-DirSize
  16. .Example
  17.   # Create a tab-separated text file of Folders and Sizes
  18.         PS> 'Folder', 'Size' -join "`t" > folder_sizes.txt
  19.         PS> Get-DirSize C:\MyFolder | Sort-Object Size -desc |
  20.         >>    %{$_.Folder, $_.Size -join "`t"} >> folder_sizes.txt
  21. .ReturnValue
  22.   An object with Folder and Size properties.
  23. #>
  24.   param([Parameter(Mandatory = $true, ValueFromPipeline = $true)][string]$path)
  25.   BEGIN {}
  26.  
  27.   PROCESS{
  28.     $size = 0
  29.     $folders = @()
  30.  
  31.     foreach ($file in (Get-ChildItem $path -Force -ea SilentlyContinue)) {
  32.       if ($file.PSIsContainer) {
  33.         $subfolders = @(Get-DirSize $file.FullName)
  34.         $size += $subfolders[-1].Size
  35.         $folders += $subfolders
  36.       } else {
  37.         $size += $file.Length
  38.       }
  39.     }
  40.  
  41.     $object = New-Object -TypeName PSObject
  42.     $object | Add-Member -MemberType NoteProperty -Name Folder `
  43.                          -Value (Get-Item $path).FullName
  44.     $object | Add-Member -MemberType NoteProperty -Name Size -Value $size
  45.     $folders += $object
  46.     Write-Output $folders
  47.   }
  48.  
  49.   END {}
  50. }

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me