PoshCode Archive  Artifact [f7ea81cc88]

Artifact f7ea81cc88b1a8a109bbbe04121a0afc440d1b8f0ccf30e1de5a9f3618ea073d:

  • File Get-DirSize.ps1 — part of check-in [08dda2fd03] at 2018-06-10 12:56:36 on branch trunk — A v2.0 function to recursively get the sizes of all subdirectories under a root path. (user: tojo2000 size: 1921)

# encoding: ascii
# api: powershell
# title: Get-DirSize
# description: A v2.0 function to recursively get the sizes of all subdirectories under a root path.
# version: 0.1
# type: function
# author: tojo2000
# license: CC0
# function: Get-DirSize
# x-poshcode-id: 1185
# x-archived: 2016-08-14T13:39:53
# x-published: 2009-06-30T13:32:00
#
#
function Get-DirSize {
<#
.Synopsis
  Gets a list of directories and sizes.
.Description
  This function recursively walks the directory tree and returns the size of 
  each directory found.
.Parameter path
  The path of the root folder to start scanning.
.Example
  # Get the largest folder under the user profile
  PS> (Get-DirSize $env:userprofile | sort Size)[-1]
.Example
  # Get the folder sizes of all folders under each folder in $folders
	PS> $folders | Get-DirSize
.Example
  # Create a tab-separated text file of Folders and Sizes
	PS> 'Folder', 'Size' -join "`t" > folder_sizes.txt
	PS> Get-DirSize C:\MyFolder | Sort-Object Size -desc | 
	>>    %{$_.Folder, $_.Size -join "`t"} >> folder_sizes.txt 
.ReturnValue
  An object with Folder and Size properties.
#>
  param([Parameter(Mandatory = $true, ValueFromPipeline = $true)][string]$path)
  BEGIN {}
 
  PROCESS{
    $size = 0
    $folders = @()
  
    foreach ($file in (Get-ChildItem $path -Force -ea SilentlyContinue)) {
      if ($file.PSIsContainer) {
        $subfolders = @(Get-DirSize $file.FullName)
        $size += $subfolders[-1].Size
        $folders += $subfolders
      } else {
        $size += $file.Length
      }
    }
  
    $object = New-Object -TypeName PSObject
    $object | Add-Member -MemberType NoteProperty -Name Folder `
                         -Value (Get-Item $path).FullName
    $object | Add-Member -MemberType NoteProperty -Name Size -Value $size
    $folders += $object
    Write-Output $folders
  }
  
  END {}
}