Compacting VHD of a Linux Host

At home I use Linux exclusively in virtual machines under Windows. Call me spoiled but I still use Windows as my main OS.

Since I have multiple machines quite often I use dynamic disks (Microsoft VHD format) so I can fit them all on my notebook. With usage some of them simply grow to large and a compact is needed.

In order for compact to work, we need to zero-out all free disk space. While dd is a popular choice, I personally prefer zerofree. As always, first step is to install it:

$ sudo apt-get install zerofree

Again, there are ways to do it on-line but I prefer to play it safe. Upon system reboot, just press <Shift> and you'll be greeted by Grub's menu. Go to Recovery and select root. Once single user prompt is shown, everything is ready for zerofree:

$ zerofree /dev/sda1

Once command has completed (and it'll take a while) shut machine down.

As Linux virtual machine is powered off we are ready for Windows part. Everything here is done in the diskpart:

DISKPART> select vdisk file "C:\VMs\Mint\Mint.vhd"
DiskPart successfully selected the virtual disk file.

DISKPART> attach vdisk readonly
DiskPart successfully attached the virtual disk file.

DISKPART> compact vdisk
DiskPart successfully compacted the virtual disk file.

After this is done, your virtual disk should be much smaller than before.

Leave a Reply

Your email address will not be published. Required fields are marked *