Skip to content

Instantly share code, notes, and snippets.

@janderudder
Last active April 30, 2025 13:55
Show Gist options
  • Save janderudder/e90d3348650811ecb75beefaf593bf62 to your computer and use it in GitHub Desktop.
Save janderudder/e90d3348650811ecb75beefaf593bf62 to your computer and use it in GitHub Desktop.
Reclaim WSL's virtual disk unused space

Reclaim WSL's unused virtual disk space

Compact a WSL distro's virtual disk to reclaim unused storage space.

WSL's virtual disk grows when needed but doesn't shrink by itself. Here is how to reclaim the unused space. This can sometimes free hundreds of GBs for use on Windows.

Trim the WSL partition

First, trim the partition in a WSL terminal

sudo fstrim -v /mnt/wslg/distro

If this is not the path to the right mount point, find it with findmnt -A.

Find the disk file

We need to find WSL' virtual disk file, a .vhdx file, probably named ext4.vhdx.

To do that, get your distro's name in a Windows terminal

wsl --list

Example: openSUSE-Tumbleweed

Then do that in PowerShell, replacing <distro name> with the relevant value:

(Get-ChildItem -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Lxss | Where-Object { $_.GetValue("DistributionName") -eq '<distro name>' }).GetValue("BasePath") + "\ext4.vhdx"

Compact the disk file

On Windows Pro

In a terminal

wsl --shutdown
optimize-vhd -Path <path to ext4.vhdx> -Mode full

On Windows Home

In a terminal

wsl --shutdown
diskpart

This will open a diskpart terminal in which you type

select vdisk file=<path to ext4.vhdx>
compact vdisk
exit

Configure WSL auto-shrink (experimental)

At time of writing, these two configurations need the newest experimental version of WSL. Install it with wsl --update --pre-release. Note: you still need to do the compact process to reclaim previously used space.

  • set virtual disk to sparse mode

      wsl --manage openSUSE-Tumbleweed --set-sparse true
    
  • set future distros disk to sparse: put the following in %USERPROFILE%\.wslconfig

      [experimental]
      sparseVhd=true
    

sources

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment