Compact WSL disk storage to reclaim space
If you use WSL a lot, you might have noticed something annoying where the disk space never seems to come back.
You clean up a bunch of Docker images, delete a huge node_modules folder or drop some big datasets… and yet your drive is still just as full as before.
That’s because WSL stores everything in a virtual disk (a .vhdx file) that grows on demand but never shrinks on its own. Deleting files inside your Linux environment frees the space inside the disk, but the .vhdx keeps hogging that space on the Windows side.
To actually reclaim it, you have to compact the virtual disk manually.
Find your WSL disk
First, you need the path to your distribution’s .vhdx file. It usually lives somewhere like:
%LOCALAPPDATA%\Packages\<DistroPackageName>\LocalState\ext4.vhdx
If you are not sure of the exact folder, you can list your installed distributions and search for the file:
Get-ChildItem -Path $env:LOCALAPPDATA\Packages -Recurse -Filter "ext4.vhdx" -ErrorAction SilentlyContinue | Select-Object FullName
Keep that full path handy, you will need it in the script below.
The script
Here is a small PowerShell script that automates the whole thing. It shuts down WSL, attaches the disk as read-only, compacts it and detaches it once done.
Save it as Compact-WSL.ps1:
# Shut down WSL
wsl --shutdown
# Define the diskpart commands
$diskpartCommands = @"
select vdisk file="path/to/image.vhdx"
attach vdisk readonly
compact vdisk
detach vdisk
"@
# Run diskpart with the commands
$diskpartCommands | diskpart
Write-Output "Done!"
Just replace path/to/image.vhdx with the path you found earlier.
Run it
Open a PowerShell terminal as Administrator (diskpart needs elevated privileges) and run:
.\Compact-WSL.ps1
⚠️ Make sure WSL is fully shut down and nothing is using the disk before compacting. The script already calls
wsl --shutdown, but close any WSL terminal, VS Code Remote session or Docker Desktop that might be holding a lock on the file.
Once it’s done, you should see the size of your .vhdx drop and that space finally handed back to Windows.
Not the most elegant solution, but it does the trick until WSL learns to clean up after itself 😄