With this Self-elevate script you can compact multiple vhdx at once.
# Self-elevate the script if required
if (-Not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator')) {
if ([int](Get-CimInstance -Class Win32_OperatingSystem | Select-Object -ExpandProperty BuildNumber) -ge 6000) {
$CommandLine = "-File `"" + $MyInvocation.MyCommand.Path + "`" " + $MyInvocation.UnboundArguments
Start-Process -FilePath PowerShell.exe -Verb Runas -ArgumentList $CommandLine
Exit
}
}
#Full Path of vhdx file
$d1 = #Ex: "E:\Docker\wsl\data\ext4.vhdx"
$d2 = ""
$d3 = ""
$d4 = ""
$d5 = ""
$d6 = ""
$paths = $d1, $d2, $d3, $d4, $d5, $d6
foreach ($file in $paths) {
echo ""
echo "Befor Shrinking File sizes in MB"
Get-ChildItem -Path $file | Select-Object FullName, @{Name = "Size"; E = { $_.Length / 1MB } }
echo ""
echo "---------"
echo "Shrinking $file"
echo "---------"
wsl --shutdown
Optimize-VHD -Path $file -Mode Full
echo ""
echo "After Shrinking File sizes in MB"
Get-ChildItem -Path $file | Select-Object FullName, @{Name = "Size"; E = { $_.Length / 1MB } }
echo ""
echo ""
echo ""
echo ""
}
Read-Host -Prompt "Press Enter to exit"
btw, With a little tweak you can also run it on startup ("Start Docker when you login" should be disabled)