Skip to content

Instantly share code, notes, and snippets.

@ctrlMarcio
Created May 29, 2025 21:31
Show Gist options
  • Select an option

  • Save ctrlMarcio/e2bf348a7b90ea8649085f324d510ca5 to your computer and use it in GitHub Desktop.

Select an option

Save ctrlMarcio/e2bf348a7b90ea8649085f324d510ca5 to your computer and use it in GitHub Desktop.
PowerShell script to compact the VHDX file of a WSL2 distribution to reclaim disk space on Windows. Requires manual update of the VHDX path and running as Administrator.
# Script to compact the VHDX for a WSL distribution (e.g., ext4.vhdx)
#
# WHY: WSL2 VHDX files grow dynamically but don't shrink automatically when files
# are deleted within the Linux environment. This script helps reclaim that space.
#
# USAGE:
# 1. (Optional but Recommended) Clean up files inside your WSL distro first.
# From within WSL:
# sudo apt-get update && sudo apt-get upgrade -y
# sudo apt-get autoremove -y && sudo apt-get autoclean -y
# sudo rm -rf /tmp/* /var/tmp/*
# # If you use Docker in WSL:
# # docker system prune -a --volumes
#
# 2. Manually find your ext4.vhdx path.
# Typically: C:\Users\<YourUsername>\AppData\Local\Packages\<DistroPackageName>\LocalState\ext4.vhdx
# Example for Ubuntu: C:\Users\YourUser\AppData\Local\Packages\CanonicalGroupLimited.Ubuntu_somerandomstring\LocalState\ext4.vhdx
#
# 3. !!! IMPORTANT: Update the $vhdxPath variable below with YOUR EXACT VHDX PATH. !!!
#
# 4. Run this script from an ELEVATED PowerShell prompt (Right-click PowerShell -> Run as Administrator).
# You may need to set Execution Policy: Set-ExecutionPolicy RemoteSigned -Scope Process
# --- CONFIGURATION ---
# !!! REPLACE THIS PATH WITH THE ACTUAL PATH TO YOUR ext4.vhdx FILE !!!
$vhdxPath = "C:\Users\<YourUser>\AppData\Local\Packages\CanonicalGroupLimited.Ubuntu_79rhkp1fndgsc\LocalState\ext4.vhdx" # <-- Example, CHANGE THIS
# --- END CONFIGURATION ---
# Check if running as Administrator
if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
Write-Error "This script must be run as Administrator."
Write-Host "Please re-run this script from an elevated PowerShell prompt."
Start-Sleep -Seconds 5
Exit 1
}
# Check if the VHDX file exists
if (-NOT (Test-Path $vhdxPath)) {
Write-Error "VHDX file not found at: $vhdxPath"
Write-Host "Please verify the path in the script (line starting with '$vhdxPath =') and ensure the file exists."
Start-Sleep -Seconds 5
Exit 1
}
Write-Host "Attempting to shut down WSL..."
wsl --shutdown
Write-Host "WSL shutdown command issued. Waiting 10 seconds for services to stop..."
Start-Sleep -Seconds 10 # Give WSL time to fully shut down
Write-Host "Starting diskpart operations for: $vhdxPath"
# Create a temporary multiline string for diskpart commands
$diskpartScriptContent = @"
select vdisk file="$vhdxPath"
attach vdisk readonly
compact vdisk
detach vdisk
exit
"@
# Pipe the script content to diskpart
Write-Host "Executing diskpart commands..."
$diskpartScriptContent | diskpart
If ($LASTEXITCODE -eq 0) {
Write-Host "Diskpart operations completed successfully."
Write-Host "Your WSL VHDX should now be compacted."
} Else {
Write-Warning "Diskpart operations may have encountered an error. Exit code: $LASTEXITCODE"
Write-Warning "Common causes: WSL not fully shut down (file in use), incorrect VHDX path, or insufficient permissions."
}
Write-Host "Script finished."
Read-Host "Press Enter to exit"
@ctrlMarcio
Copy link
Author

thank you fr bro I strugled with disk space on my work machine for so long I learned how to do diskpart and do this manually . but I updated docker and coudlnt figure out how to reclaim space agaian. This helped me so much thank you for posting this <3

Awesome, I'm really happy it was useful for you! Thanks for the kind words :)

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