How to Get a Folder Size in PowerShell

📜Part of the PowerShell Complete Guide, every PowerShell post on this site, grouped by the job you are doing.
The short answer

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


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.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Looking for SQL Server?

This site started as a SQL Server blog in 2017 and the archive is still here. The new SQL Server writing, and all the scripts, moved to a site of their own.

sqldba.blogScripts, error library, wait types, SSMS
Browse by topic