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

PowerShell
$path = "C:\Windows\Logs"
$size = Get-ChildItem -Path $path -Recurse -File -ErrorAction SilentlyContinue | Measure-Object -Property Length -Sum
"{0} files, {1} MB" -f $size.Count, [math]::Round($size.Sum / 1MB, 2)

Here it is on a small demo folder:

Measure-Object summing the file sizes in D:\Logs and printing the file count and size in MB
PowerShell measuring C:\Windows\Logs with Get-ChildItem and Measure-Object, returning 239 files, 92.25 MB

-Recurse includes subfolders and -File keeps directory entries out of the count, which is what makes the total match what Explorer eventually reports. -ErrorAction SilentlyContinue skips anything your account is not allowed to read, which a system folder like C:\Windows\Logs usually has.

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:

PowerShell
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.

Want it as a report? Tell Claude which folders to check, what size counts as too big and where the output should go, and ask for the script. Try it on a small folder before you point it at a whole drive.

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 *