Pipe Get-ChildItem -Recurse -File into Measure-Object -Property Length -Sum, then divide by 1MB or 1GB.
Right-clicking a folder and waiting for Windows to finish counting is fine once. When you are trying to work out what filled a server disk at 2am, you want the answer for every folder at once, sorted.
The One-Liner
$path = "D:\Logs"
$size = Get-ChildItem -Path $path -Recurse -File | Measure-Object -Property Length -Sum
"{0} files, {1} MB" -f $size.Count, [math]::Round($size.Sum / 1MB, 2)
-Recurse includes subfolders and -File keeps directory entries out of the count, which is what makes the total match what Explorer eventually reports.
Every Subfolder, Biggest First
This is the version worth keeping. It reports each immediate subfolder as its own row, sorted by size, so the culprit is at the top:
Get-ChildItem -Path "D:\" -Directory |
Select-Object Name,
@{Name = "SizeMB"; Expression = {
[math]::Round((Get-ChildItem $_.FullName -Recurse -File -ErrorAction SilentlyContinue |
Measure-Object -Property Length -Sum).Sum / 1MB, 2)
}} |
Sort-Object SizeMB -Descending |
Format-Table -AutoSize
-ErrorAction SilentlyContinue matters here. Without it, one folder your account cannot read stops the whole thing with a wall of red.
Two Things That Catch People Out
An empty folder returns nothing, not zero. Measure-Object on an empty set gives a $null sum, so [math]::Round($null / 1MB, 2) returns 0 rather than failing, but a total that reads 0 might mean empty rather than small.
Size on disk is a different number. This measures the logical file size. Compression, sparse files and cluster slack all mean the space actually reclaimed can differ from what you see here.
Related
- List Files with Sizes and Dates
- Delete Files Older Than a Given Age
- Show Available Disk Space in SQL Server
- PowerShell Complete Guide
If SQL Server is part of your day job, my current work lives over at sqldba.blog: production DBA scripts, an error library and the SSMS guide.
Leave a Reply