Find Largest (Or Smallest) Files In A Directory Or Drive With PowerShell

1 minute read September 8, 2014

One of our SQL servers was running low on disk space and I needed to quickly find the largest files on the drive to know what was eating up all of the disk space, so I wrote this PowerShell line that I thought I would share:

# Get all files sorted by size.
Get-ChildItem -Path 'C:\SomeFolder' -Recurse -Force -File | Select-Object -Property FullName,@{Name='SizeGB';Expression={$_.Length / 1GB}},@{Name='SizeMB';Expression={$_.Length / 1MB}},@{Name='SizeKB';Expression={$_.Length / 1KB}} | Sort-Object { $_.SizeKB } -Descending | Out-GridView

If you are still only running PowerShell 2.0, it will complain that it doesn’t know what the -File switch is, so here’s the PowerShell 2.0 compatible version (which is a bit slower):

# Get all files sorted by size.
Get-ChildItem -Path 'C:\SomeFolder' -Recurse -Force | Where-Object { !$_.PSIsContainer } | Select-Object -Property FullName,@{Name='SizeGB';Expression={$_.Length / 1GB}},@{Name='SizeMB';Expression={$_.Length / 1MB}},@{Name='SizeKB';Expression={$_.Length / 1KB}} | Sort-Object { $_.SizeKB } -Descending | Out-GridView

Just change ‘C:\SomeFolder’ to the folder/drive that you want scanned, and it will show you all of the files in the directory and subdirectories in a GridView sorted by size, along with their size in GB, MB, and KB. The nice thing about using a GridView is that it has built in filtering, so you can quickly do things like filter for certain file types, child directories, etc.

Here is a screenshot of the resulting GridView:

Files Sorted By Size

And again with filtering applied (i.e. the .bak at the top to only show backup files):

Files Sorted By Size And Filtered

All done with PowerShell; no external tools required.

Happy Sys-Adminning!

Comments

deadlydog

@Dino Ah yes, the -File was introduced in PowerShell v3.0, so if you are still running 2.0 it will throw an error.

Without that flag you will get back both files and directories. To just get the files, replace “-File” with “| Where-Object { !$_.PSIsContainer } |”.

netkid

@jalapenico

use this: Get-ChildItem -Path $somePath | Where-Object { !$_.PSIsContainer } # Get files only.

from http://dans-blog.azurewebsites.net/powershell-2-0-vs-3-0-syntax-differences-and-more/

Kevin Michael Fries

Just learning this so working off a great example that’s practical is really spot on.

I’ll be playing with it for prompting for drive/directory and how many (First XXX)

But it’s a fantastic intro to this.

PS: Just a DBA but want to hone my Windows skills without writing programs using C#. .net or VB.

Leave a Comment

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

Loading...