Skip to content

Instantly share code, notes, and snippets.

@jjmartres
Last active April 22, 2024 09:35
Show Gist options
  • Save jjmartres/bb283ea479909b2e1088dd7d27046b3e to your computer and use it in GitHub Desktop.
Save jjmartres/bb283ea479909b2e1088dd7d27046b3e to your computer and use it in GitHub Desktop.
How to Shrink a WSL2 Virtual Disk

How to Shrink a WSL2 Virtual Disk

Before you begin

Before shrinking a WSL2 virtual disk, you need to ensure that WSL2 is not running.

You can check if it’s running with the command wsl.exe --list --verbose in PowerShell:

PS C:\Users\valorin> wsl.exe --list --verbose
  NAME            STATE           VERSION
* WLinux          Running         2
  Debian          Stopped         2
  Ubuntu-18.04    Stopped         2
  kali-linux      Stopped         2

It should stop when it’s idle, or you can encourage it to stop with the wsl.exe --terminate command:

PS C:\Users\valorin> wsl.exe --terminate WLinux

WARNING : I highly recommend you take a backup of your WSL2 installation. These instructions worked for me, but you could have a different environment that may result in corrupted data. So please, take a backup first!

Use diskpart to Shrink a WSL2 Virtual Disk

I discovered you can use the diskpart tool to compact a VHDX. This allows you to shrink a WSL2 virtual disk file, reclaiming disk space. It appeared to work for me without any data corruption, taking the file size down from 100GB to 15GB. Your results may vary though.

You can launch the diskpart tool in PowerShell:

PS C:\Users\valorin> diskpart

It will open up a new window:

diskpart.exe

Once that has opened, you need to specify the path to your VHDX file.

If you don’t know this path, you can find by first locating the package directory for your WSL2 instance, which lives in: C:\Users\username\AppData\Local\Packages\. Look for the vendor name, such as WhitewaterFoundryLtd.Co for Pengwin, CanonicalGroupLimited for Ubuntu, or TheDebianProject for Debian. Once you’ve identified the folder, you’ll find the VHDX in the LocalState subdirectory.

For me, this path is:

C:\Users\username\AppData\Local\Packages\WhitewaterFoundryLtd.Co.16571368D6CFF_kd...\LocalState\ext4.vhdx

With the full path to the VHDX, you can select it within diskpart:

DISKPART> select vdisk file="C:\Users\myusername\AppData\Local\Packages\WhitewaterFoundryLtd.Co.16571368D6CFF_kd...\LocalState\ext4.vhdx"

DiskPart successfully selected the virtual disk file.

Once it’s selected, you can ask diskpart to compact it:

DISKPART> compact vdisk

  100 percent completed

DiskPart successfully compacted the virtual disk file.	

Once that has finished, you can close diskpart.

@damonb123
Copy link

I had to run "Stop-Service -name LxssManager" to use "compact vdisk"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment