September 2023 update: A new pre-release of WSL (2.0.0) is reported to provide a new "sparse" mode for disk images which will automatically shrink the image when files are removed.
While I have not tested this personally yet, from the DevBlog announcement, you can convert an existing disk image to sparse with the following command from PowerShell:
wsl --manage <distro> --set-sparse true
You can also add the following to your .wslconfig
(located in your Windows profile directory, not inside WSL) to have any newly created distro image be sparse:
[experimental]
sparseVhd=true
Older answer:
There's a WSL Github issue open on this topic. WSL will automatically grow the virtual disk (ext4.vhdx), but shrinking it to reclaim unused space is something that must currently be done manually.
The first thing you'll need to do is know the location of your ext4.vhdx. For a default Ubuntu installation, it should be in something like %USERPROFILE%\AppData\Local\Packages\CanonicalGroupLimited.UbuntuonWindows_79rhkp1fndgsc\LocalState\
Then there are several techniques that you can use to remove the unused space. I recommend you start with a wsl --shutdown
and copy the vhdx as a backup to start. If you are running Docker Desktop, also shut it down, otherwise it may inadvertently attempt to restart WSL after your --shutdown
.
If you are on Windows Professional or higher, you can install Hyper-V and use the Optimize-VHD commandlet as described in the original issue.
.
On Windows Home (and higher) you can use diskpart
as described in this comment.
Exporting the WSL distro and re-importing it into a new WSL instance (as in this comment) will also reclaim the space. Note that you will need to reset the default username after an import. See here (and here for alternative options).
I have tested and confirmed both the second and third techniques personally.