Skip to content

Instantly share code, notes, and snippets.

@dungsaga
Last active October 31, 2023 17:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dungsaga/be1194af3eb4f13d7de56c35e46ccdda to your computer and use it in GitHub Desktop.
Save dungsaga/be1194af3eb4f13d7de56c35e46ccdda to your computer and use it in GitHub Desktop.
reduce size of a WSL virtual disk

Reduce size with diskpart

You should run PowerShell as Administrator (otherwise diskpart won't be able to received the piped commands)

$vhdx_path = '%USERPROFILE%\AppData\Local\Packages\CanonicalGroupLimited.UbuntuonWindows_79rhkp1fndgsc\LocalState\ext4.vhdx'

@"
select vdisk file=$vhdx_path
compact vdisk
"@ | diskpart

source: https://stackoverflow.com/questions/64772243/can-diskpart-take-command-line-parameters-or-can-i-fake-them-with-powershell That's all, folks!

If diskpart shows access error, you should run wsl --shutdown and detach the VHD in Disk Management.

PS: Registered WSL instances are recorded under registry key HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Lxss. For example, UbuntuonWindows is under HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Lxss\{17e7343c-a823-4a5c-a44d-a795a7546d62}. You can change the BasePath to move it to another disk, or change DefaultEnvironment or KernelCommandLine to modify how it boot up.

Reduce size more with wsl

Compacted VHD can be further reduced in size:

# export it to a tar file
wsl --terminate UbuntuonWindows
wsl --export UbuntuonWindows d:\wsl-backup\UbuntuonWindows.tar

# unregister it if you want to import to the same Linux installation
wsl --unregister UbuntuonWindows

# import from tar file
wsl --import UbuntuonWindows d:\path-to\linux-installation-folder d:\wsl-backup\UbuntuonWindows.tar
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment