Skip to content

Instantly share code, notes, and snippets.

@diversen
Last active April 25, 2024 12:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save diversen/6747b165bf083eaa78411e262492c64f to your computer and use it in GitHub Desktop.
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\SomeUser\AppData\Local\Packages\CanonicalGroupLimited.Ubuntu_abcd\LocalState\ext4.vhdx"
# Shut down WSL to ensure no files are in use
wsl --shutdown
# Only is the disk is space Optimize-VHD will work
fsutil sparse setflag $vdiskPath 0
# Optimize the VHDX file
Optimize-VHD -Path $vdiskPath -Mode Full
# Use DiskPart to compact the VHD
$diskPartCommands = @"
select vdisk file "$vdiskPath"
compact vdisk
"@
# Create a temporary script for DiskPart
$diskPartScriptPath = "diskpart-script.txt"
$diskPartCommands | Set-Content -Path $diskPartScriptPath
# Execute DiskPart with the script
diskpart /s $diskPartScriptPath
# Optional: Clean up the DiskPart script
Remove-Item -Path $diskPartScriptPath
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment