Last active
August 7, 2024 08:46
-
-
Save diversen/6747b165bf083eaa78411e262492c64f to your computer and use it in GitHub Desktop.
Optimize and compact a vhdx file using powerscript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Close all works on wsl before running the script as the script will shutdown wsl | |
# | |
# Define the path to the VHDX file | |
# You will need to find the location of the ext4.vhdx to comact | |
$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