Skip to main content

How to calculate the average file size for a given path (directory) in PowerShell.

# Based off StackExchange: Average file size statistics (https://superuser.com/a/643542)

$files = Get-ChildItem -Path 'C:\installers' -File -Recurse
$totalSize = (($files | Measure-Object -Property Length -Sum).Sum / 1MB)
$averageSize = ($totalSize / $files.Count)

$outputObject = New-Object -TypeName PSCustomObject -Property @{
  Path        = 'C:\installers'
  Files       = $files.Count.ToString('N0')
  TotalSize   = ('{0:N2} MB' -f $totalSize)
  AverageSize = ('{0:N2} MB' -f $averageSize)
}

$outputObject | Format-List
# Path        : C:\installers
# Files       : 19,520
# TotalSize   : 31,438.40 MB
# AverageSize : 1.61 MB