Along with Visual Studio Code, Windows Subsystem for Linux (WSL) is a godsend. It makes it easy to access a Linux system without needing to install Linux on the host machine or use a virtual machine. It is indeed a virtual machine, but the way Microsoft integrates it into Windows is slick.
The problem is that WSL uses a virtual disk as storage, which previously retained its size on the host machine even when files inside the virtual disk were no longer there. Newer WSL releases will use a sparse disk to address this problem automatically. However, the old version requires setting the flag manually.
C:\Users\faruq>wsl --list --verbose
NAME STATE VERSION
* Ubuntu-22.04 Stopped 2
docker-desktop-data Stopped 2
docker-desktop Stopped 2
Solution #1: Use diskpart to compact the vdisk size
Microsoft DiskPart version 10.0.22621.1
Copyright (C) Microsoft Corporation.
On computer: BITWISE
DISKPART> select vdisk file=C:\Users\faruq\AppData\Local\Packages\CanonicalGroupLimited.Ubuntu22.04LTS_79rhkp1fndgsc\LocalState\ext4.vhdx
DiskPart successfully selected the virtual disk file.
DISKPART> compact vdisk
100 percent completed
DiskPart successfully compacted the virtual disk file.
DISKPART>
Below are pictures comparing the size before and after the compact command. However, there is not much difference because before I wrote this article, I had already compacted the vdisk and reclaimed 50GB.
Solution #2: Set vdisk as sparse
Another solution is to simply set the WSL distro to use a sparse vdisk and let the system do the job.
C:\Users\faruq>wsl --manage Ubuntu-22.04 --set-sparse false
Conversion in progress, this may take a few minutes.
The operation completed successfully.
If you try to compact it like the previous solution, you will get an error:
DISKPART> compact vdisk
DiskPart has encountered an error: The requested operation could not be completed due to a virtual disk system limitation. Virtual hard disk files must be uncompressed and unencrypted and must not be sparse.
See the System Event Log for more information.
See you later!