Skip to content

Windows / WSL 2 / PowerShell

I deleted the files. Windows still showed the disk as full.

My WSL virtual disk had grown to 545 GiB. Linux was using 56 GiB, but the VHDX would not shrink. This is the sanitized PowerShell script that returned 444 GiB to Windows.

Why this happens

Deleting files is only half the job.

WSL 2 stores each Linux distro in a dynamically expanding VHDX. The file grows as Linux needs space. Large deletes free blocks inside Linux, but the Windows VHDX can stay at its old size.

The detail that fixed my case was the mount mode. Microsoft notes that Full mode defaults to Prezeroed unless the VHDX is attached read-only. The script trims Linux, shuts WSL down, attaches the disk read-only, then runs the Full compaction pass.

What it does

Four deliberate steps.

No file cleanup is hidden inside the script. It only prepares and compacts free space that already exists.

  1. 01

    Find the real disks

    The script reads the WSL registry for the current Windows user. No distro path or username is baked in.

  2. 02

    Mark free blocks

    It runs fstrim inside each selected distro. This marks already-free Linux blocks for the virtual disk layer.

  3. 03

    Compact offline

    It shuts down WSL, mounts each VHDX read-only, and runs Optimize-VHD in Full mode.

  4. 04

    Measure the result

    It reports the before and after sizes and writes a timestamped log to the Windows Desktop.

Run it

Read the targets before saying yes.

  1. 01Download the script to a Windows folder, such as Downloads.
  2. 02Close WSL terminals, remote editor windows, and Explorer windows open to \\wsl$.
  3. 03Open PowerShell in that folder. Run the command and approve the administrator prompt.
  4. 04Check every target path and size. Enter y only when they are the disks expected.

Compact the default WSL 2 distro

powershell.exe -ExecutionPolicy Bypass -File .\compact-wsl-vhdx.ps1

Compact one named distro

powershell.exe -ExecutionPolicy Bypass -File .\compact-wsl-vhdx.ps1 -DistroName Ubuntu

Compact every WSL 2 distro

powershell.exe -ExecutionPolicy Bypass -File .\compact-wsl-vhdx.ps1 -AllDistros

Include Docker Desktop's WSL disk

powershell.exe -ExecutionPolicy Bypass -File .\compact-wsl-vhdx.ps1 -IncludeDocker

Before running it

  • Back up anything important inside WSL.
  • Check that Optimize-VHD is available in the Hyper-V PowerShell module.
  • Keep Windows awake and do not interrupt compaction.
  • The script stops before compaction when a selected disk is still mounted.

If it fails

  • Error 0x80070020 means an app still has the VHDX open. Close every WSL client and retry.
  • A missing Hyper-V module stops the script before it shuts WSL down.
  • A successful compact can reclaim nothing when the disk has no eligible free blocks.
  • Sparse, compressed, or encrypted VHDX files may need a different Windows-supported path.

Source

The complete script.

The code shown here is the same source used by Copy and Download. Read it before running it.

compact-wsl-vhdx.ps1
[CmdletBinding()]
param(
    [string[]]$DistroName,
    [switch]$AllDistros,
    [switch]$IncludeDocker,
    [switch]$Force
)

$ErrorActionPreference = 'Stop'
Set-StrictMode -Version Latest

$lxssRegistryPath = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Lxss'

function Test-IsAdministrator {
    $identity = [Security.Principal.WindowsIdentity]::GetCurrent()
    $principal = [Security.Principal.WindowsPrincipal]::new($identity)
    return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}

function Get-FileSizeGiB([string]$Path) {
    if (-not (Test-Path -LiteralPath $Path)) {
        return $null
    }

    return [math]::Round((Get-Item -LiteralPath $Path).Length / 1GB, 2)
}

function Get-SystemDriveFreeGiB {
    $driveName = $env:SystemDrive.TrimEnd(':')
    return [math]::Round((Get-PSDrive -Name $driveName).Free / 1GB, 2)
}

function ConvertTo-NormalWindowsPath([string]$Path) {
    $expanded = [Environment]::ExpandEnvironmentVariables($Path)
    if ($expanded.StartsWith('\\?\')) {
        return $expanded.Substring(4)
    }

    return $expanded
}

function Get-WslDistributions {
    if (-not (Test-Path -LiteralPath $lxssRegistryPath)) {
        throw 'No WSL distributions were found for the current Windows user.'
    }

    $rootKey = Get-Item -LiteralPath $lxssRegistryPath
    $defaultDistribution = [string]$rootKey.GetValue('DefaultDistribution')
    $distributions = @()

    foreach ($key in Get-ChildItem -LiteralPath $lxssRegistryPath) {
        $distributionName = [string]$key.GetValue('DistributionName')
        $distributionBasePath = [string]$key.GetValue('BasePath')
        if (-not $distributionName -or -not $distributionBasePath) {
            continue
        }

        $version = [int]$key.GetValue('Version', 1)
        if ($version -ne 2) {
            continue
        }

        $basePath = ConvertTo-NormalWindowsPath $distributionBasePath
        $vhdPath = Join-Path $basePath 'ext4.vhdx'
        if (-not (Test-Path -LiteralPath $vhdPath)) {
            continue
        }

        $distributions += [pscustomobject]@{
            Name = $distributionName
            VhdPath = $vhdPath
            IsDefault = [string]$key.PSChildName -ieq [string]$defaultDistribution
        }
    }

    return @($distributions | Sort-Object Name)
}

function Select-WslDistributions {
    param(
        [object[]]$Distributions,
        [string[]]$RequestedNames,
        [bool]$SelectAll
    )

    if ($SelectAll -and $RequestedNames.Count -gt 0) {
        throw 'Use either -AllDistros or -DistroName, not both.'
    }

    if ($SelectAll) {
        return @($Distributions)
    }

    if ($RequestedNames.Count -gt 0) {
        $selected = @()
        foreach ($name in $RequestedNames) {
            $match = @($Distributions | Where-Object { $_.Name -ieq $name })
            if ($match.Count -ne 1) {
                $available = ($Distributions.Name -join ', ')
                throw "WSL 2 distro '$name' was not found. Available: $available"
            }

            $selected += $match[0]
        }

        return @($selected)
    }

    $default = @($Distributions | Where-Object { $_.IsDefault })
    if ($default.Count -eq 1) {
        return $default
    }

    if ($Distributions.Count -eq 1) {
        return @($Distributions[0])
    }

    $available = ($Distributions.Name -join ', ')
    throw "No default WSL 2 distro could be resolved. Pass -DistroName or -AllDistros. Available: $available"
}

function Get-DockerVhdPath {
    $candidates = @(
        (Join-Path $env:LOCALAPPDATA 'Docker\wsl\disk\docker_data.vhdx'),
        (Join-Path $env:LOCALAPPDATA 'Docker\wsl\data\ext4.vhdx')
    )

    foreach ($candidate in $candidates) {
        if (Test-Path -LiteralPath $candidate) {
            return $candidate
        }
    }

    return $null
}

if (-not (Get-Command wsl.exe -ErrorAction SilentlyContinue)) {
    throw 'wsl.exe was not found. This script requires WSL 2 on Windows.'
}

if (-not (Test-IsAdministrator)) {
    Write-Host 'Requesting administrator permission...'

    $stagedScript = Join-Path $env:TEMP 'compact-wsl-vhdx.ps1'
    Copy-Item -LiteralPath $PSCommandPath -Destination $stagedScript -Force

    $powerShellPath = "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe"
    $arguments = @(
        '-NoExit'
        '-NoProfile'
        '-ExecutionPolicy', 'Bypass'
        '-File', ('"{0}"' -f $stagedScript)
    )

    if ($AllDistros) {
        $arguments += '-AllDistros'
    }
    elseif (@($DistroName).Count -gt 0) {
        $arguments += '-DistroName'
        foreach ($name in $DistroName) {
            $arguments += ('"{0}"' -f $name.Replace('"', '\"'))
        }
    }

    if ($IncludeDocker) {
        $arguments += '-IncludeDocker'
    }
    if ($Force) {
        $arguments += '-Force'
    }

    $null = Start-Process -FilePath $powerShellPath -Verb RunAs -WindowStyle Normal -ArgumentList $arguments
    exit 0
}

Import-Module Hyper-V -ErrorAction Stop

$allDistributions = @(Get-WslDistributions)
if ($allDistributions.Count -eq 0) {
    throw 'No WSL 2 ext4.vhdx files were found for the current Windows user.'
}

$requestedNames = if ($null -eq $DistroName) { @() } else { @($DistroName) }
$selectedDistributions = @(Select-WslDistributions `
    -Distributions $allDistributions `
    -RequestedNames $requestedNames `
    -SelectAll $AllDistros.IsPresent)

$targets = @()
foreach ($distribution in $selectedDistributions) {
    $targets += [pscustomobject]@{
        Kind = 'WSL'
        Name = $distribution.Name
        Path = $distribution.VhdPath
        SizeBeforeGiB = Get-FileSizeGiB $distribution.VhdPath
    }
}

$dockerCommand = $null
$dockerVhdPath = $null
if ($IncludeDocker) {
    $dockerCommand = Get-Command docker.exe -ErrorAction SilentlyContinue
    if (-not $dockerCommand) {
        throw 'Docker Desktop CLI was not found. Remove -IncludeDocker or install Docker Desktop.'
    }

    $dockerVhdPath = Get-DockerVhdPath
    if (-not $dockerVhdPath) {
        throw 'Docker Desktop WSL data disk was not found.'
    }

    $targets += [pscustomobject]@{
        Kind = 'Docker'
        Name = 'Docker Desktop'
        Path = $dockerVhdPath
        SizeBeforeGiB = Get-FileSizeGiB $dockerVhdPath
    }
}

$desktop = [Environment]::GetFolderPath('Desktop')
$timestamp = Get-Date -Format 'yyyyMMdd-HHmmss'
$logPath = Join-Path $desktop "compact-wsl-vhdx-$timestamp.log"
$transcriptStarted = $false
$dockerStopped = $false
$failures = @()
$systemDriveFreeBefore = Get-SystemDriveFreeGiB

try {
    Start-Transcript -Path $logPath -Force | Out-Null
    $transcriptStarted = $true
}
catch {
    Write-Warning "Could not start transcript: $($_.Exception.Message)"
}

try {
    Write-Host ''
    Write-Host 'Targets:'
    foreach ($target in $targets) {
        Write-Host "  $($target.Name): $($target.SizeBeforeGiB) GiB"
        Write-Host "    $($target.Path)"
    }

    Write-Host ''
    Write-Host 'This script trims free blocks, shuts down WSL, and compacts the selected virtual disks.'
    Write-Host 'It does not delete files or prune Docker data.'
    Write-Host 'Close WSL terminals, remote editor windows, and Explorer windows open to \\wsl$ before continuing.'

    if (-not $Force) {
        $answer = Read-Host 'Continue? [y/N]'
        if ($answer -notmatch '^(y|yes)$') {
            Write-Host 'Cancelled. No changes were made.'
            exit 0
        }
    }

    foreach ($distribution in $selectedDistributions) {
        Write-Host ''
        Write-Host "Trimming free blocks inside $($distribution.Name)..."
        & wsl.exe -d $distribution.Name -u root -- fstrim -v /
        if ($LASTEXITCODE -ne 0) {
            throw "fstrim failed for $($distribution.Name) with exit code $LASTEXITCODE"
        }
    }

    if ($IncludeDocker) {
        Write-Host ''
        Write-Host 'Stopping Docker Desktop...'
        & docker.exe desktop stop
        if ($LASTEXITCODE -ne 0) {
            throw "Docker Desktop stop failed with exit code $LASTEXITCODE"
        }
        $dockerStopped = $true
    }

    Write-Host ''
    Write-Host 'Shutting down WSL...'
    & wsl.exe --shutdown
    if ($LASTEXITCODE -ne 0) {
        throw "WSL shutdown failed with exit code $LASTEXITCODE"
    }
    Start-Sleep -Seconds 5

    $runningDistributions = @(& wsl.exe --list --running --quiet 2>$null) |
        ForEach-Object { ($_ -replace [char]0, '').Trim() } |
        Where-Object { $_ }
    if ($runningDistributions.Count -gt 0) {
        throw "WSL restarted before compaction. Still running: $($runningDistributions -join ', ')"
    }

    foreach ($target in $targets) {
        try {
            $diskImage = Get-DiskImage -ImagePath $target.Path -ErrorAction SilentlyContinue
            if ($diskImage -and $diskImage.Attached) {
                throw 'The virtual disk is still attached after WSL shutdown.'
            }

            Write-Host ''
            Write-Host "Compacting $($target.Name)..."
            $mountedReadOnly = $false
            try {
                Mount-VHD -Path $target.Path -ReadOnly -NoDriveLetter
                $mountedReadOnly = $true
                Optimize-VHD -Path $target.Path -Mode Full
            }
            finally {
                if ($mountedReadOnly) {
                    Dismount-VHD -Path $target.Path
                }
            }
        }
        catch {
            $message = "$($target.Name): $($_.Exception.Message)"
            $failures += $message
            Write-Warning $message
        }
    }
}
catch {
    $failures += $_.Exception.Message
    Write-Warning $_.Exception.Message
}
finally {
    if ($dockerStopped) {
        Write-Host ''
        Write-Host 'Starting Docker Desktop...'
        & docker.exe desktop start
        if ($LASTEXITCODE -ne 0) {
            $failures += "Docker Desktop start failed with exit code $LASTEXITCODE"
        }
    }
}

$systemDriveFreeAfter = Get-SystemDriveFreeGiB

Write-Host ''
Write-Host "System drive free before: $systemDriveFreeBefore GiB"
Write-Host "System drive free after:  $systemDriveFreeAfter GiB"
Write-Host "Change: $([math]::Round($systemDriveFreeAfter - $systemDriveFreeBefore, 2)) GiB"
Write-Host ''
Write-Host 'Virtual disk sizes:'
foreach ($target in $targets) {
    $sizeAfter = Get-FileSizeGiB $target.Path
    $change = [math]::Round($target.SizeBeforeGiB - $sizeAfter, 2)
    Write-Host "  $($target.Name): $($target.SizeBeforeGiB) GiB -> $sizeAfter GiB ($change GiB reclaimed)"
}

$exitCode = 0
if ($failures.Count -gt 0) {
    Write-Warning "Completed with $($failures.Count) failure(s)."
    foreach ($failure in $failures) {
        Write-Warning "  $failure"
    }
    $exitCode = 1
}
else {
    Write-Host 'Done.'
}

Write-Host "Log saved to $logPath"
if ($transcriptStarted) {
    Stop-Transcript | Out-Null
}

exit $exitCode