Skip to content

Instantly share code, notes, and snippets.

@kipavy
Last active April 25, 2025 16:34
Show Gist options
  • Select an option

  • Save kipavy/fb858118c2b373369741ac084c6c3d45 to your computer and use it in GitHub Desktop.

Select an option

Save kipavy/fb858118c2b373369741ac084c6c3d45 to your computer and use it in GitHub Desktop.
# PowerShell script to find and compact WSL2's ext4.vhdx file
# Stop all WSL2 instances
wsl --shutdown
# Get the user's profile path
$userProfile = [System.Environment]::GetFolderPath("UserProfile")
# Path to WSL2 distributions
$wslPath = "$userProfile\AppData\Local\Packages"
# Find the ext4.vhdx file within all distributions
$ext4VhdxPaths = Get-ChildItem -Path $wslPath -Recurse -Filter "ext4.vhdx" -ErrorAction SilentlyContinue
# Check if the ext4.vhdx file was found
if ($ext4VhdxPaths.Count -eq 0) {
Write-Host "No ext4.vhdx file found. Make sure WSL2 is installed."
exit
}
# Loop through each found .vhdx file (in case there are multiple distributions)
foreach ($ext4Vhdx in $ext4VhdxPaths) {
Write-Host "Found ext4.vhdx file at: $($ext4Vhdx.FullName)"
# Diskpart commands to attach, compact, and detach the VHDX
$diskpartScript = @"
select vdisk file="$($ext4Vhdx.FullName)"
attach vdisk readonly
compact vdisk
detach vdisk
"@
# Save diskpart commands to a temporary file
$tempDiskpartScriptPath = [System.IO.Path]::GetTempFileName()
Set-Content -Path $tempDiskpartScriptPath -Value $diskpartScript
# Run diskpart with the script
diskpart /s $tempDiskpartScriptPath
# Remove the temporary script
Remove-Item $tempDiskpartScriptPath -Force
# Optimize the VHDX file
Optimize-VHD -Path $ext4Vhdx.FullName -Mode Full
Write-Host "Compaction and optimization of $($ext4Vhdx.FullName) complete."
}
Write-Host "All operations completed successfully."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment