Skip to content

Instantly share code, notes, and snippets.

@Trass3r
Last active August 3, 2023 12:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Trass3r/435b4647a721c9f52c5f8e02d0a63dac to your computer and use it in GitHub Desktop.
Save Trass3r/435b4647a721c9f52c5f8e02d0a63dac to your computer and use it in GitHub Desktop.
Reduces disk space taken by the WSL and Docker vhdx files
$ErrorActionPreference = "Stop"
$files = Get-ChildItem -Path C:\Users -Recurse -Include "ext4.vhdx" -Force -ErrorAction SilentlyContinue | Select-Object FullName, Length
wsl -u root fstrim /
foreach ($file in $files) {
echo "Compacting $file"
wsl --shutdown
Mount-VHD -Path $file.FullName -ReadOnly
Optimize-VHD -Path $file.FullName -Mode Full
Dismount-VHD $file.FullName
}
Get-ChildItem -Path C:\Users -Recurse -Include "ext4.vhdx" -Force -ErrorAction SilentlyContinue | Select-Object FullName, Length
@cmorty
Copy link

cmorty commented Dec 19, 2020

You can change wsl sudo fstrim / to wsl -u root fstrim /, saving you the trouble of messing with sudoers.

@Trass3r
Copy link
Author

Trass3r commented Mar 18, 2021

Another issue that may occur is if your admin account is different from the normal user account.
Then wsl won't find the installed distributions.

And execution policies may get in your way:

powershell.exe -ExecutionPolicy Bypass .\CompressWSLdisks.ps1

@g2p
Copy link

g2p commented Aug 3, 2023

For some windows editions, you don't have the VHD commandlets, instead you can do:

$ErrorActionPreference = "Stop"

Get-ChildItem -Path C:\Users -Recurse -Include "ext4.vhdx" -Force -ErrorAction SilentlyContinue | Select-Object FullName, Length

wsl -u root fstrim /
wsl --shutdown

diskpart
# Type the rest in the diskpart terminal that just opened
select vdisk file="C:\WSL-Distros\…\ext4.vhdx"
attach vdisk readonly
compact vdisk
detach vdisk
exit

From microsoft/WSL#4699 (comment)

@Trass3r
Copy link
Author

Trass3r commented Aug 3, 2023

Yeah you can install them manually even on Home editions if you search for smth like "windows home hyperv install".

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