Skip to content

Instantly share code, notes, and snippets.

@cptSwing
Last active March 16, 2022 17:19
Show Gist options
  • Save cptSwing/f042d960764b3b3e33cbed05175f4425 to your computer and use it in GitHub Desktop.
Save cptSwing/f042d960764b3b3e33cbed05175f4425 to your computer and use it in GitHub Desktop.
Windows PowerShell script to compact WSL's virtual hd - run PowerShell as admin
# before running, execute Set-ExecutionPolicy RemoteSigned so that your PowerShell will allow it to run
$ErrorActionPreference="Stop"
Write-Host "Cleaning up packages and fstrim - " -NoNewLine
$SUDOSECUREPASSWORD = Read-Host "please enter your sudo password" -AsSecureString
Write-Host ""
# convert to usable String
$SUDOPASSWORD = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($SUDOSECUREPASSWORD))
Write-Host "Running: sudo apt autoremove"
wsl echo $SUDOPASSWORD `| sudo -S 2`>/dev/null apt autoremove; Write-Host ""
Write-Host "Running: sudo apt autoclean"
wsl echo $SUDOPASSWORD `| sudo -S 2`>/dev/null apt autoclean; Write-Host ""
Write-Host "Running: sudo apt clean"
wsl echo $SUDOPASSWORD `| sudo -S 2`>/dev/null apt clean; Write-Host ""
Write-Host "Running: sudo fstrim /"
wsl echo $SUDOPASSWORD `| sudo -S 2`>/dev/null fstrim -v /; Write-Host ""
$DISTROS = @('Debian','Ubuntu','Kali', 'SUSE')
$PACKAGESDIR = $Env:LOCALAPPDATA+"\Packages"
do {
$CONTINUEPROMPT = Read-Host "WARNING! This script will terminate all running WSL2 virtual machines. Continue? [y/n]"
# $CONTINUEPROMPT = Read-Host -NoNewLine "WARNING! This script will terminate all running WSL2 virtual machines. Continue? [y/n]"
if(($CONTINUEPROMPT -eq "N") -or ($CONTINUEPROMPT -eq "n")) {
exit
}
if(($CONTINUEPROMPT -eq "Y") -or ($CONTINUEPROMPT -eq "y")) {
break
}
} while (($CONTINUEPROMPT -ne "N") -or ($CONTINUEPROMPT -ne "n") -or ($CONTINUEPROMPT -ne "Y") -or ($CONTINUEPROMPT -ne "y"))
#shut down the WSL2 core
Write-Host "Shutting down the WSL2 core..."
wsl --shutdown
foreach ($DISTRO in $DISTROS) {
Write-Host "Currently looking for distribution: "$DISTRO
#Set up a command to search for the installed package name of the distrubtion"
$DIRLISTCMD = "dir -Name "+$PACKAGESDIR+"\*"+$DISTRO+"*"
$DISTRODIRS = Invoke-Expression -Command $DIRLISTCMD
if(!$DISTRODIRS) {
Write-Host "No installed distributions for "$DISTRO
} else {
Write-Host "Distrubtion located at "$PACKAGESDIR"\"$DISTRODIRS
Write-Host "Starting distribution virtual disk compaction..."
$DISKPARTCMD = @"
select vdisk file="$PACKAGESDIR\$DISTRODIRS\LocalState\ext4.vhdx"
attach vdisk readonly
compact vdisk
detach vdisk
exit
"@
$DISKPARTCMD | diskpart
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment