Tested script

Find the largest files under a folder (PowerShell)

Lists the biggest files under a folder and all its subfolders, largest first. Reach for it when a drive is filling up and you need to know what is taking the space.

Tested

The script

<#
.SYNOPSIS
    Lists the largest files under a folder.
.DESCRIPTION
    Searches a folder and all of its subfolders, then shows the biggest files
    first. Folders you cannot read are skipped and counted, not fatal.
    Read-only: nothing is moved or deleted.
.PARAMETER Path
    The folder to search. Defaults to the current folder.
.PARAMETER Top
    How many files to show. Defaults to 20.
.EXAMPLE
    ./Get-LargestFile.ps1 -Path C:\Users -Top 10
.EXAMPLE
    ./Get-LargestFile.ps1 -Path /var/log | Export-Csv big-files.csv -NoTypeInformation
#>
[CmdletBinding()]
param(
    [string]$Path = (Get-Location).Path,
    [ValidateRange(1, 10000)]
    [int]$Top = 20
)

if (-not (Test-Path -LiteralPath $Path -PathType Container)) {
    Write-Error "Folder not found: $Path"
    exit 1
}

$accessErrors = @()
$files = Get-ChildItem -LiteralPath $Path -File -Recurse -Force `
    -ErrorAction SilentlyContinue -ErrorVariable accessErrors

if ($accessErrors.Count -gt 0) {
    Write-Warning "Skipped $($accessErrors.Count) item(s) that could not be read."
}

if (-not $files) {
    Write-Warning "No files found under $Path"
    exit 0
}

$files |
    Sort-Object -Property Length -Descending |
    Select-Object -First $Top -Property @(
        @{ Name = 'SizeMB'; Expression = { [math]::Round($_.Length / 1MB, 2) } },
        'LastWriteTime',
        'FullName'
    )

Run it

./Get-LargestFile.ps1 -Path C:\Users -Top 10
./Get-LargestFile.ps1 -Path /var/log | Export-Csv big-files.csv -NoTypeInformation

How it works

Parameters

-Path is the folder to search and defaults to where you are now. -Top is how many files to show. [ValidateRange(1, 10000)] makes PowerShell reject silly values like 0 before any of your code runs.

Check the folder exists

Test-Path -PathType Container confirms the path is a real folder. If not, the script writes an error and exits with code 1, so a scheduled task can tell it failed.

Collect the files

Get-ChildItem -File -Recurse -Force walks every subfolder. -Force includes hidden files, which is often where the space goes. Folders you cannot open would normally spray red errors, so -ErrorAction SilentlyContinue hides them and -ErrorVariable collects them. The script then prints one warning saying how many it skipped, so you know the list may be incomplete.

Sort and pick

Sort-Object -Property Length -Descending puts the biggest first. Select-Object -First $Top keeps just the top of the list, and a calculated property turns bytes into megabytes. The output is objects, not text, so you can pipe it straight into Export-Csv or Where-Object.