Skip to content

Instantly share code, notes, and snippets.

@brentk
Created August 3, 2026 22:27
Show Gist options
  • Select an option

  • Save brentk/f663dcfbf8a0ec5f90eec7755495b066 to your computer and use it in GitHub Desktop.

Select an option

Save brentk/f663dcfbf8a0ec5f90eec7755495b066 to your computer and use it in GitHub Desktop.
Docker (Windows) Cleanup
# View space taken up
docker system df -v
# Safe cleanup commands (won't drop anything that is "dangling" because a container is just stopped)
docker image prune
docker builder prune
# PS Function to shrink WSL drive (run as administrator)
function docker_compact {
param(
[string]$VhdxPath = "$env:LOCALAPPDATA\Docker\wsl\disk\docker_data.vhdx"
)
# Ensure running as administrator
$isAdmin = (
[Security.Principal.WindowsPrincipal] `
[Security.Principal.WindowsIdentity]::GetCurrent()
).IsInRole(
[Security.Principal.WindowsBuiltInRole]::Administrator
)
if (-not $isAdmin) {
Write-Host ""
Write-Host "This function must be run from an elevated PowerShell session." -ForegroundColor Red
Write-Host "Please reopen PowerShell as Administrator and try again."
Write-Host ""
return
}
Write-Host ""
Write-Host "!!!!!!!!!!!!!!!!!!!!!!!!!!!" -ForegroundColor Yellow
Write-Host ""
Write-Host "ENSURE DOCKER IS NOT RUNNING" -ForegroundColor Yellow
Write-Host ""
Write-Host "!!!!!!!!!!!!!!!!!!!!!!!!!!!" -ForegroundColor Yellow
Write-Host ""
Read-Host "Press Enter to continue"
if (-not (Test-Path $VhdxPath)) {
Write-Error "VHDX file not found: $VhdxPath"
return
}
$beforeSizeBytes = (Get-Item $VhdxPath).Length
$beforeSizeGB = [math]::Round($beforeSizeBytes / 1GB, 2)
Write-Host ""
Write-Host "Current VHDX size: $beforeSizeGB GB"
Write-Host ""
Write-Host "Shutting down WSL..."
wsl --shutdown
$diskpartScript = @"
select vdisk file="$VhdxPath"
attach vdisk readonly
compact vdisk
detach vdisk
exit
"@
$tempFile = New-TemporaryFile
try {
Set-Content -Path $tempFile -Value $diskpartScript
Write-Host ""
Write-Host "Running diskpart..."
diskpart /s $tempFile
if ($LASTEXITCODE -ne 0) {
Write-Error "diskpart failed with exit code $LASTEXITCODE"
return
}
$afterSizeBytes = (Get-Item $VhdxPath).Length
$afterSizeGB = [math]::Round($afterSizeBytes / 1GB, 2)
$savedBytes = $beforeSizeBytes - $afterSizeBytes
$savedGB = [math]::Round($savedBytes / 1GB, 2)
Write-Host ""
Write-Host "Compaction complete." -ForegroundColor Green
Write-Host "Before: $beforeSizeGB GB"
Write-Host "After : $afterSizeGB GB"
Write-Host "Saved : $savedGB GB"
Write-Host ""
}
finally {
if (Test-Path $tempFile) {
Remove-Item $tempFile -Force
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment