Last active
August 4, 2024 20:30
-
-
Save Trass3r/435b4647a721c9f52c5f8e02d0a63dac to your computer and use it in GitHub Desktop.
Reduces disk space taken by the WSL and Docker vhdx files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$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 |
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
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
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
You can change
wsl sudo fstrim /
towsl -u root fstrim /
, saving you the trouble of messing with sudoers.