Functions/Get-FolderSize.ps1
function Get-FolderSize { [CmdletBinding()] param ( [Parameter()] [string] $Path = ".", [Parameter()] [int] $Depth = 0, [Parameter()] [switch] $IncludeFiles ) function Get-FolderSizePerItem { [CmdletBinding()] param ( [Parameter(Mandatory)] [string] $Path ) $Path = Resolve-Path $Path function Format-ItemSize { [CmdletBinding()] param ( [Parameter(Mandatory)] [float] $size ) if ($size -gt 1024 * 1024 * 1024) { $size = $size / 1024 / 1024 / 1024 $UnitOfMeasurement = "GB" } elseif ($size -gt 1024 * 1024) { $size = $size / 1024 / 1024 $UnitOfMeasurement = "MB" } elseif ($size -gt 1024) { $size = $size / 1024 $UnitOfMeasurement = "kB" } else { $UnitOfMeasurement = "B" } $size = [math]::Round($size, 2) $returnSize = "$($size.ToString()) $UnitOfMeasurement" return $returnSize } $Results = @() $TotalSize = 0 $SizeBytes = 0 $Files = Get-ChildItem $Path -Recurse -File -Force -ErrorAction SilentlyContinue $Files | ForEach-Object { # $_.Length $TotalSize += $_.Length $SizeBytes += $_.Length } $Results += [PSCustomObject]@{ Path = $Path Type = "Folder" TotalSize = Format-ItemSize $TotalSize TotalItems = ($Files).Count SizeBytes = $SizeBytes } if ($IncludeFiles) { $Files = Get-ChildItem $Path -File -Force -ErrorAction SilentlyContinue $Files | ForEach-Object { $Results += [PSCustomObject]@{ Path = $_.FullName Type = "File" TotalSize = Format-ItemSize $_.Length TotalItems = 1 SizeBytes = $_.Length } } } return $Results } if ($Depth -ge 1) { $Result = @() Get-ChildItem -Path $Path -Depth ($Depth - 1) -Directory -ErrorAction SilentlyContinue | ForEach-Object { $Result += Get-FolderSizePerItem $_.FullName } } else { $Result = Get-FolderSizePerItem $Path } return $Result } |