Knowledge - Details


How to compact a VHDX containing a Linux OS
Date Added: 12/6/2016

If you use Hyper-V and have a Linux-based guest OS configured with a dynamically-expanding VHDX file, then you might find that it's hard to compact the VHDX once it has grown.  Hyper-V's built-in compact tool doesn't seem to make any difference.  However, there is a way!

1) On the guest, run these commands:
     a)    sudo apt-get install secure-delete
     b)    cd /
     c)    sudo sfill -llz .
     d)    sudo shutdown -h now
2) On the host, run the Optimize command in powershell:
     a)   (replace the path in the following command with your path to the VHDX file on the host)
     b)   gci -File -Filter *.vhd* -Path D:\VMs -Recurse | % {Mount-VHD $_.FullName -ReadOnly; Optimize-VHD $_.FullName -Mode full; Dismount-VHD $_.FullName}

The sfill command can take many hours or days to complete.  It basically overwrites the free space in the ;inux file system with zeros.

The powershell command should be much faster, taking only a few minutes, and reduces the size of the VHDX file by removing all those zeros.  Leave the Hyper-V server running and the guest VM powered off while the Optimize command is running.

As soon as the Optimize command is finished, you should see that the VHDX file is much smaller depending on how much free space was available on the linux file system.



Back to List

Disclaimer: Everything on this website is written for my own use. I disclaim any guarantees that the procedures and advice listed here are accurate, safe, or beneficial for anyone else. If you attempt to follow any procedures or advice shared here, you do it at your own risk. Part of IT work is knowing how to recover from problems.