Shrinking and Compacting WSL Storage
Day by day, our WSL storage or virtual disk grows larger, taking up more system space and eventually causing storage issues. To avoid this, we need to shrink and compact it.
If you’ve been using WSL (Windows Subsystem for Linux) for a while, you might notice something annoying: "your storage keeps disappearing".
Day by day, the WSL virtual disk (ext4.vhdx) grows bigger, even if you’ve deleted files inside Linux. The problem is that WSL doesn’t automatically shrink the disk, so your Windows storage slowly gets eaten up 😵💫.
But, you can shrink and compact the WSL virtual disk manually, and It's pretty easy.
This guide works for WSL2
1. Open your PowerShell
Open the powershell in your windows, recommended if you run as administrator.
3. Run DiskPart
If the command failed try to manually enable the Hyper-V
powershelldiskpart
after run that, you will see something like this in the terminal (or it maybe will open the new window of the terminal)
powershell1Microsoft DiskPart version 10.0.26100.1150 2 3Copyright (C) Microsoft Corporation. 4On computer: ARDHPTR21 5 6DISKPART>
4. Select the WSL Virtual Disk
Usually the Virtual Disk is named as ext4.vdisk. The location if this file is depends in where you install the WSL, but usually if you not setting up anything it will located under %USERPROFILE%\AppData\Local\Packages\, and there is will be listed the WSL Distro that you installed, ex: C:\Users\<YourUser>\AppData\Local\Packages\CanonicalGroupLimited.Ubuntu_79rhkp1fndgsc\LocalState\ext4.vhdx
Then you can run this command inside the diskpart
powershellDISKPART> select vdisk file="C:\Users\<YourUser>\AppData\Local\Packages\...\LocalState\ext4.vhdx"
5. Attach the disk to readonly
powershellDISKPART> attach vdisk readonly
6. Start shrinking
powershellDISKPART> compact vdisk
7. Finalize
Actually after you running the compact process the size of your virtual disk should be more smaller now, but last don't forget to detach and exit from the diskpart mode.
powershellDISKPART: detach vdisk DISPART: exit
And... you're done🔥