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.
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
.
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"
In a terminal
wsl --shutdown
optimize-vhd -Path <path to ext4.vhdx> -Mode full
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
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
- microsoft/WSL#4699
- https://superuser.com/questions/1606213/how-do-i-get-back-unused-disk-space-from-ubuntu-on-wsl2
- https://writeabout.net/2021/10/14/shrink-your-wsl2-virtual-disk-on-windows-home/
- https://opensource.com/article/20/2/trim-solid-state-storage-linux
- https://learn.microsoft.com/en-us/windows/wsl/disk-space#how-to-locate-the-vhdx-file-and-disk-path-for-your-linux-distribution