PowerShell Fun: Recursive Folder Size
Here's the basic script I came up with:
function Get-ChildItemSizes(){
ls | % -Begin { $results = @() } -Process {
$size = ls $_ -Recurse |
measure -Sum -Property Length -ErrorAction SilentlyContinue |
select -ExpandProperty Sum
$thisOne = New-Object System.Object
$thisOne | Add-Member -Type NoteProperty -Name "Directory" -Value $_.Name
$thisOne | Add-Member -Type NoteProperty -Name "Size" -Value $size
$results += $thisOne
} -End { Write-Output $results }
}
This gives is the following sample output result set:
PS:\ Get-ChildItemSizes Directory Size --------- ---- Folder B 578 Folder C 23 Folder A 1031
This is exactly the form we're looking for, as it allows us to answer questions such as "Show me the largest folder tree", which translates into this:
PS:\ Get-ChildItemSizes | sort -Property Size -Decending | select -First 1 Directory Size --------- ---- Folder A 1031
Alternatively, we could answer the question os "Show me the smallest folder tree", which simply becomes this:
PS:\ Get-ChildItemSizes | sort -Property Size -Ascending | select -First 1 Directory Size --------- ---- Folder C 23
The core of this snippet is simply a data pipeline based on the output of the ls (or rather Get-ChildItem) cmdlet. Each object in this output stream is used to "dive deep" into the the recursive structure underneath, aggregating the sum of the item sizes. The remainder of the process block is simply collecting results leveraging a local collection of NoteProperty objects.
Nothing to terribly complex, but a fun little experiment nonetheless. Enjoy!!!