Skip to content

Instantly share code, notes, and snippets.

@diversen
Last active September 2, 2025 11:35
Show Gist options
  • Select an option

  • Save diversen/6747b165bf083eaa78411e262492c64f to your computer and use it in GitHub Desktop.

Select an option

Save diversen/6747b165bf083eaa78411e262492c64f to your computer and use it in GitHub Desktop.
Optimize and compact a vhdx file using powerscript
# Define the path to the VHDX file
$vdiskPath = "C:\Users\azks430\AppData\Local\Packages\CanonicalGroupLimited.Ubuntu_79rhkp1fndgsc\LocalState\ext4.vhdx"
Write-Host "Shutting down WSL..."
wsl --shutdown
# Wait until the VHDX file is no longer in use
Write-Host "Waiting for VHD to be released..."
$timeout = 30 # maximum wait time in seconds
$start = Get-Date
while ((Test-Path $vdiskPath) -and (Get-Process | Where-Object { $_.Path -eq $vdiskPath }) -and ((Get-Date) - $start).TotalSeconds -lt $timeout) {
Start-Sleep -Seconds 1
}
# Check if the file is free
if (Get-Process | Where-Object { $_.Path -eq $vdiskPath }) {
Write-Error "VHDX file is still in use after $timeout seconds. Please close any applications that may be using it and try again."
exit 1
}
# Ensure the VHD is marked as sparse
Write-Host "Clearing sparse flag..."
fsutil sparse setflag $vdiskPath 0
# Optimize the VHDX
Write-Host "Optimizing VHD..."
Optimize-VHD -Path $vdiskPath -Mode Full
# Prepare DiskPart script for compaction
$diskPartCommands = @"
select vdisk file "$vdiskPath"
compact vdisk
"@
$diskPartScriptPath = "diskpart-script.txt"
$diskPartCommands | Set-Content -Path $diskPartScriptPath
# Run DiskPart to compact the VHD
Write-Host "Compacting VHD with DiskPart..."
diskpart /s $diskPartScriptPath
# Clean up temporary DiskPart script
Remove-Item -Path $diskPartScriptPath
Write-Host "VHD optimization and compaction completed successfully."
@diversen7
Copy link

You will need to enable hyper-v module:

Get-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V

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