Claiming WSL Disk Space
/ 3 min read
Table of Contents
TLDR
Shut down your WSL distributions and use PowerShell (as administrator) to run Optimize-VHD on the VHDX file used by your WSL distribution:
wsl --shutdownOptimize-VHD -Path '<Path to your VHDX file>' -Mode FullIntroduction
Working with WSL I sometimes see my disk usage grow significantly until the day I’m almost out of space and need to reclaim it somehow. In my case, the reason is that WSL uses a virtual hard disk (VHDX) file to store the file system of each distribution, and over time these files grow in size as data is added, but they don’t shrink when data is removed.
It’s easy to check whether you have this issue too. Since I always forget the path of my WSL VHDX file, I typically use PowerShell to find it:
(Get-ChildItem -Path $env:USERPROFILE\AppData\Local\Packages\ -Filter "*.vhdx" -Recurse -ErrorAction SilentlyContinue).FullNameCopy the path and store it in a variable for convenience:
$VHDXPath = '<Path to your VHDX file>'Then, check the size of the VHDX file:
"{0:N2} GB" -f ((Get-Item $VHDXPath).Length / 1GB)Now, it’s time to compare this size with the actual used space inside the WSL distribution. To do this, start your WSL distribution and run:
df -h /If the size of the VHDX file is significantly larger than the used space reported by df, then it’s definitely time to reclaim some bytes!
Optimize-VHD to the rescue
Luckily, there is a PowerShell cmdlet called Optimize-VHD that can be used to compact VHDX files. This command reclaims unused space in the VHDX file, effectively reducing its size on disk.
First of all, make sure the VHDX file is not mounted (the easiest way is to stop WSL), then run the Optimize-VHD command as administrator on the VHDX file you found earlier:
wsl --shutdownOptimize-VHD -Path $VHDXPath -Mode FullThe process may take some time depending on the size of the VHDX file and the amount of unused space to reclaim.
After the command completes, you can check the size of the VHDX file again with the same commands used above to see how much space you’ve reclaimed.
And that’s all, see you next time your disk is full!