This is a little function I wrote one day when I needed to get the total size of a set of folders (including sub folders). It performs a recursive search and computes the total count and also shows the size in a more human-readable format. It also have a “hidden” property called SizeInBytes that can be helpful if you want to do size calculations and need the size in a common format.


function Get-FolderSize{
Get the total size of a folder.
Get the total size of a folder.
Path to target folder.
Get-FolderSize .\Folder01
Will get the total size of the folder Folder01.
Name: Get-FolderSize
Author: Øyvind Kallstad
Date: 11.02.2014
Version: 1.1
UpdateNotes: 13.02.2014
Added SizeInBytes after input from Alan Seglen.
This column is hidden by default and can be used for size calculations.
[Parameter(ValueFromPipeline = $true, ValueFromPipelinebyPropertyName = $true, Mandatory = $true, HelpMessage='Enter the path to the target folder')]
[ValidateScript({Test-Path $_})]
foreach($filePath in $Path){
# get the total size of the current path
$size = Get-ChildItem $filePath Force Recurse ErrorAction 'Stop' | Measure-Object Property 'Length' Sum
# dynamically adjust the size format based on the size
{$_ -gt 1KB} {$formatedSize = '{0:n2} KB' -f ($_ / 1KB)}
{$_ -gt 1MB} {$formatedSize = '{0:n2} MB' -f ($_ / 1MB)}
{$_ -gt 1GB} {$formatedSize = '{0:n2} GB' -f ($_ / 1GB)}
{$_ -gt 1TB} {$formatedSize = '{0:n2} TB' -f ($_ / 1TB)}
DEFAULT {$formatedSize = '{0} B' -f $_}
# create output object
$output = ([PSCustomObject] [Ordered] @{
Name = $filePath
Count = $size.Count
Size = $formatedSize
SizeInBytes = $size.Sum
# customize default display properties of the object
$defaultProperties = @('Name','Count','Size')
$defaultDisplayPropertySet = New-Object System.Management.Automation.PSPropertySet('DefaultDisplayPropertySet',[string[]]$defaultProperties)
$PSStandardMembers = [System.Management.Automation.PSMemberInfo[]]@($defaultDisplayPropertySet)
$output | Add-Member MemberType MemberSet Name PSStandardMembers Value $PSStandardMembers
# write output object to pipeline
Write-Output $output
# clean-up
Remove-Variable formatedSize, Size ErrorAction 'SilentlyContinue'
# handling exceptions
Write-Warning $_.Exception.Message

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s