Jitsumi
Back to the blog

WSL 2 Disk Space Not Shrinking? How to Compact ext4.vhdx on Windows

Check the exact WSL 2 disk, verify a backup and stop the distribution before attempting VHDX compaction. Understand DiskPart, Optimize-VHD and sparse-mode limits.

A translucent smoked-glass rectangular container on a wooden desk with stacked teal and brass blocks filling only one end while the rest of the rigid case remains empty.

Deleting files inside a WSL 2 distribution can free space in Linux without reducing the size of its standard dynamically expanding ext4.vhdx file on Windows. A host-side compaction may reclaim some space after WSL is fully stopped. It is a maintenance operation on the distribution’s disk, not a guaranteed or risk-free way to recover a particular number of gigabytes.

This guide retains its February 2025 focus on a standard, non-sparse WSL 2 distribution that you manage yourself. Safety corrections were added on 29 October 2026. It is based on Microsoft’s command documentation, not a tested benchmark of your PC. Do not use these steps on Docker Desktop’s managed data disks, a damaged filesystem, an attached disk in use, or a work-managed installation without its administrator’s guidance.

Before any maintenance: save your work, stop databases and other applications cleanly, and make application-level backups where needed. Keep a verified backup outside the distribution’s VHD, with enough free space for the backup and recovery. Do not proceed if you cannot identify and recover the data you need.

In Windows PowerShell, list your distributions. Choose the exact name of your own WSL 2 distribution. After closing WSL applications and quitting Docker Desktop, shut down WSL and export that named distribution to a new backup file outside its VHD. Replace both quoted examples; the destination folder must already exist and have enough free space.

wsl.exe --list --verbose
# Replace the distribution and backup path; do not overwrite an existing backup.
wsl.exe --shutdown
wsl.exe --export "YourDistro" "D:\backups\YourDistro-before-compact.tar"

Wait for a successful export, confirm the backup exists, and verify that the files you need are recoverable. For important work, test recovery into a separately named disposable distribution and directory before touching the original disk. A successful export command alone is not proof of a usable restore. If verification fails or you lack recovery space, stop here. Never unregister the original distribution as a compaction step. Microsoft’s export and import reference.

Why Deleting Files in Linux Leaves ext4.vhdx Full on Windows

WSL 2 uses a Linux kernel in a lightweight virtual machine and stores a distribution’s ext4 filesystem in a VHDX file. Its virtual capacity is different from the host space currently occupied: Microsoft’s February 2025 documentation lists a 1 TB default maximum, with 512 GB and 256 GB defaults on earlier releases. Microsoft’s dated disk-space documentation.

Because ext4.vhdx is configured as a dynamically expanding virtual disk, two separate storage allocators are involved:

  1. The guest Linux ext4 allocator tracks which blocks inside the virtual disk are in use or free.
  2. The host VHDX container allocates storage for virtual-disk blocks; its file length and Windows space used are not the same measurement as ext4’s Used column.

Deleting a file makes its blocks reusable once Linux no longer needs them; a process holding an open deleted file can delay that. A standard dynamic VHD does not necessarily become smaller when files are removed. Sparse disks behave differently and are outside the manual workflow below.

Linux usage can fall before the Windows container becomes smaller. Actual compaction may reclaim less space, or none, and VHDX metadata and allocation overhead remain.

Step 1: Check Real Usage Inside Linux and Locate ext4.vhdx

After verifying the backup, reopen the selected WSL 2 distribution and inspect its root filesystem. This procedure does not require uninstalling packages or deleting logs. Remove only data you deliberately no longer need through the application’s own workflow.

# Run inside the selected WSL 2 distribution, after verifying its backup.
df -h /

# Request discard of currently unused filesystem blocks.
sudo fstrim -v /

fstrim asks the storage stack to discard blocks the mounted filesystem considers unused. Its reported byte count is not a promise of the reduction in the Windows file. Support and results depend on the filesystem and storage stack; read any error and do not force unsupported operations or fill the disk with zeros to chase a target size. The fstrim manual.

Read the Used column for /. It describes filesystem usage, not an exact compacted VHDX size. df -h uses powers of 1,024 for its displayed units; decimal GB uses powers of 1,000. Compare like-for-like measurements and allow for filesystem and virtual-disk overhead.

In Windows PowerShell under the Windows account that owns the distribution, resolve its registered path by exact distribution name rather than searching for every VHDX. Replace YourDistro with the name checked above. This reads the WSL registration; it does not edit the registry. Microsoft’s distribution-path lookup.

$distro = "YourDistro"
$entry = @(Get-ChildItem -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Lxss |
    Where-Object { $_.GetValue("DistributionName") -eq $distro })
if ($entry.Count -ne 1) { throw "Expected exactly one matching distribution. Stop and check its name." }
$vhd = Join-Path $entry[0].GetValue("BasePath") "ext4.vhdx"
if (-not (Test-Path -LiteralPath $vhd -PathType Leaf)) { throw "VHD not found. Stop; do not select a different disk by guesswork." }
Get-Item -LiteralPath $vhd | Select-Object FullName, Length

Record that exact FullName and its current Length. A Store installation may look like the example below, but imported or relocated distributions can be elsewhere. Do not substitute this example path for your lookup result.

C:\Users\<YourUsername>\AppData\Local\Packages\CanonicalGroupLimited.Ubuntu_79rhkp1fndgsc\LocalState\ext4.vhdx

Step 2: Shut Down WSL Completely Before Touching the Virtual Disk

Never attach or compact ext4.vhdx while a Linux distribution or background WSL 2 utility VM is still running. Modifying the virtual disk file from the host while the guest kernel has ext4 mounted read-write can corrupt the filesystem.

Save and stop applications again after the Linux check, close WSL terminals and remote editor sessions, and quit Docker Desktop before shutdown so it does not restart WSL. In Windows PowerShell, stop WSL and inspect the state: Microsoft’s WSL command reference.

wsl.exe --shutdown
wsl.exe --list --verbose

Every listed distribution must show Stopped. Do not launch a Linux shell or allow a background tool to restart WSL during compaction. If the file is in use, stop and identify what owns it rather than forcing access.

Step 3: Compact ext4.vhdx with DiskPart or Hyper-V Optimize-VHD

Choose one manual method below only after the backup, exact-path and stopped-state checks pass. Both operate on a dynamically expanding virtual disk and can complete without reducing its file size.

  • DiskPart (compact vdisk) — Microsoft documents this for Windows 10 and Windows 11. It does not require the Hyper-V PowerShell module. Select only the verified VHDX and keep it detached or attached read-only.
  • Hyper-V PowerShell (Optimize-VHD) — An alternative when the Hyper-V module is already available on a supported Windows edition. Its effective compaction mode depends on how the VHDX is attached; see the limits below.
  • Sparse VHD mode — A separate experimental feature introduced in WSL 2.0.0, not a third step to run after manual compaction. Read the historical and current safety note below before considering it.

Option A: Compact with DiskPart

Microsoft’s compact vdisk reference permits a selected dynamic VHD to be compacted while detached or attached read-only. Read-only attachment prevents mounting its filesystem for writes; compaction itself still changes the container, so the verified backup remains necessary. DiskPart compact vdisk reference.

Open an Administrator PowerShell or Command Prompt window and start diskpart. At its prompt, enter the following selection commands one at a time, replacing the path with the verified FullName from Step 1. The DISKPART> prompt is not part of a command.

select vdisk file="C:\full\verified\path\ext4.vhdx"
detail vdisk

Check the selected path and disk details before continuing. If selection fails or the details do not identify the expected distribution, stop. Then enter these commands one at a time. If attachment fails, do not continue to compact. If compaction reports an error, retain the exact error and detach the disk you attached before investigating.

attach vdisk readonly
compact vdisk
detach vdisk
exit

Wait for each command to complete. Duration varies with the disk and available storage; there is no fixed completion-time promise. Confirm detach vdisk succeeds before restarting WSL. Do not use clean, format, delete or other DiskPart commands as part of this procedure.

Option B: Compact with PowerShell Optimize-VHD (Windows Pro, Enterprise, and Education)

If the Hyper-V PowerShell module is already installed, the following is an alternative for the same verified, stopped and detached VHDX. Microsoft documents that requesting Full on a VHDX that is not attached read-only falls back to Prezeroed mode. The command below therefore does not guarantee a full scan, and it may reclaim no space. Do not run both methods merely because the first recovered less than expected. Microsoft’s dated Optimize-VHD reference.

# Elevated Windows PowerShell; use the verified, stopped, detached VHDX.
# Full falls back to Prezeroed when this VHDX is not attached read-only.
Optimize-VHD -Path "C:\full\verified\path\ext4.vhdx" -Mode Full

If Optimize-VHD is unavailable, do not install a full virtualization stack just for this task. Use the documented DiskPart method if its prerequisites are met, or stop and ask the administrator responsible for the machine.

What About Automatic Shrinking with sparseVhd?

Microsoft introduced sparse-VHD support as an opt-in experimental feature in September 2023. Its intent was automatic reclamation, distinct from standard dynamic VHD compaction. That historical announcement is not a guarantee that conversion is safe or supported on your installed WSL build. September 2023 WSL announcement.

The original experiment offered a distribution-level set-sparse command and a sparseVhd setting for newly created disks. These are not necessary for the manual workflow above; this guide does not recommend enabling them as a quick fix.

Retrospective safety note (29 October 2026): Microsoft’s WSL source contains a warning that sparse VHD support is disabled because of potential data corruption. If your build displays a warning or refuses conversion, stop rather than bypassing that protection. Do not force sparse conversion to reclaim space from a distribution containing work you need. Microsoft WSL warning in the merged source change.

Common Pitfalls and Quick Verification

If compaction fails or reclaims less than expected, keep the backup and investigate the specific result:

  • File-in-use error: a WSL application or background integration may have reopened the disk. Close those applications normally, stop WSL again and confirm its state. Do not repeatedly force compaction against an open file.
  • WSL fails to start: first check whether the exact VHDX remains attached in DiskPart and detach it if necessary. Mount errors have other causes too; an error code alone does not prove this diagnosis. If errors remain, stop modifying the disk and use Microsoft’s WSL repair guidance or restore from the verified backup with qualified help.
  • Successful operation but little or no reduction: check that you measured the same VHDX, that the Linux discard request succeeded, and whether processes still held deleted files open before shutdown. Compaction is not guaranteed to reduce file size. Do not assume a large Docker-managed disk belongs to this distribution or apply these commands to it.

After confirming the VHDX is detached, measure the same file’s Length again, then start the named distribution and run df -h /. Check that your actual files and applications still work, not only that Linux boots. Keep the backup until that verification is complete. A smaller host file is useful only if the environment remains intact.

Share this post