[CmdletBinding()] param( [Parameter(Mandatory = $true)] [string]$Path, [ValidateRange(1, 500)] [int]$Top = 20, [string]$Csv ) $ErrorActionPreference = 'Stop' if (-not (Test-Path -LiteralPath $Path -PathType Container)) { throw "Folder not found: $Path" } $root = (Resolve-Path -LiteralPath $Path).Path $rows = @() foreach ($folder in Get-ChildItem -LiteralPath $root -Directory -ErrorAction SilentlyContinue) { $files = @(Get-ChildItem -LiteralPath $folder.FullName -File -Recurse -ErrorAction SilentlyContinue) $sum = ($files | Measure-Object -Property Length -Sum).Sum if ($null -eq $sum) { $sum = 0 } $rows += [pscustomobject]@{ Folder = $folder.Name SizeMB = [math]::Round($sum / 1MB, 2) Files = $files.Count FullName = $folder.FullName } } if ($rows.Count -eq 0) { Write-Host 'No subfolders found.' exit 0 } $totalSizeMB = [math]::Round((($rows | Measure-Object -Property SizeMB -Sum).Sum), 2) $rows = @($rows | Sort-Object -Property SizeMB -Descending | Select-Object -First $Top) $rows | Format-Table -AutoSize Write-Host "Total size: $totalSizeMB MB" if ($Csv) { $csvPath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Csv) $rows | Export-Csv -LiteralPath $csvPath -NoTypeInformation -Encoding UTF8 Write-Host "Report saved: $csvPath" }