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

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

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:

FilesSortedBySize

 

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

FilesSortedBySizeAndFiltered

All done with PowerShell; no external tools required.

Happy Sys-Adminning!

  1. Dino
    January 28th, 2015 at 10:43 | #1

    Thanks for sharing. Seems like parameter -File generates error and should be removed.
    Regards!

  2. January 28th, 2015 at 12:23 | #2

    @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 } |”.

  3. jalapenico
    May 19th, 2016 at 13:24 | #3

    and to only get back directories?

  4. netkid
    November 27th, 2016 at 04:37 | #4

    @jalapenico

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

    from http://blog.danskingdom.com/powershell-2-0-vs-3-0-syntax-differences-and-more/

  5. netkid
    November 27th, 2016 at 04:38 | #5

    @jalapenico
    sorry, it was this, of course:

    Get-ChildItem -Path $somePath | Where-Object { $_.PSIsContainer } # Get directories only.

  1. March 2nd, 2016 at 09:42 | #1