Deleting files inside WSL doesn't shrink the disk they lived on
Deleting files inside WSL doesn't shrink the disk they lived on WSL2 keeps its entire Linux filesystem inside one file on the Windows side, a virtual hard disk with a .vhdx extension. Run cargo clean inside WSL, watch du report gigabytes freed, check the size of that .vhdx file on the Windows host afterward, and it hasn't moved. Not shrunk a little. Not moved at all. That gap confused me the…
Files left behind inside the Windows Subsystem for Linux (WSL) do not automatically reduce the disk size they occupy. Inside WSL2, the Linux filesystem resides within a single virtual hard disk file, a .vhdx extension. After executing the `cargo clean` command inside WSL and checking the size of the .vhdx file with `du` on the Windows host, the size remains unchanged.
This discrepancy arises due to the nature of thin-provisioned virtual disks, which grow dynamically as the filesystem inside requires more blocks. When those blocks become available for reuse within the container, the host container does not automatically release space.
To manually reduce the container file's size, three steps must be performed in a specific order: first, run `fstrim` inside WSL to mark the freed blocks as discardable; second, execute `wsl --shutdown` to release the virtual machine's hold on the file; finally, use the `Optimize-VHD -Mode Full` command on the Windows side or `diskpart`'s `compact vdisk` to physically shrink the container file. Skipping any of these steps will not result in a size reduction.
For example, on a heavily-used WSL container, the disk initially measured 726.25GB, but only 648GB of that was actively used by the filesystem. After a thorough cleanup, the container's size decreased by 672GB to 173.4GB. This reduction was confirmed by comparing the file size directly before and after the compaction, rather than relying on a tool's summary.
However, this single compaction does not guarantee ongoing size reduction, as additional data may be written to the guest filesystem, causing the container to fill back up.
Automating the compaction process revealed a minor issue: a scheduled task version of the compaction script failed silently due to improper permission requests from within a Task Scheduler- launched elevated process. The solution involved explicitly checking `IsInRole(Administrator)` instead of requesting permissions again. Additionally, running the compaction while checking WSL's status in the same session inadvertently restarted the WSL VM.
This reminder highlights the importance of carefully monitoring the system during testing to avoid unintended side effects.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.