Compacting VirtualBox VDI files

A large maximum dynamic disk size for a VirtualBox guest is problematic. Even if one uses a small portion of that maximum size, the guest OS (especially Windows) will spread itself out. A 10 GB Windows image will climb to the maximum size of the dynamic VDI file over time (say to 50 GB).

Here’s a fairly painless procedure to fix this, taking less than 1 hour on a modern PC. I assume your guest OS is Windows, and your host OS is Linux running VirtualBox.

BACKUP THE VDI FILE BEFORE DOING THIS PROCEDURE!

In guest Windows, run Disk Defragmenter

In guest Windows, in Command Prompt, run

sdelete -z c:

Shutdown guest Windows, and “insert” the Gparted ISO file by right-clicking the CD icon at the bottom of the guest OS VirtualBox window and selecting your ISO file.

Resize guest Windows partition so that you have only say 8 GB free (e.g. original partition 40 GB, only 10 GB used –> resize to 18 GB)

Reboot guest Windows, removing the Gparted ISO file from VirtualBox. You will see Windows automatically runs CheckDisk–this is normal. You will need to reboot guest Windows once more, then shutdown guest Windows

In host Linux Terminal:

cd ~/VirtualBox*/WinXP

(or wherever the .VDI file is located). Then type in Terminal

vboxmanage modifyhd --compact MyFile.vdi

where MyFile.vdi is the name of your VDI file.

Observe that the VDI file size has dropped a lot!

Defragment in guest Windows actually makes host VDI file INCREASE in size by the amount of bytes that were moved to defragment! Repeat steps 1, 2, and 6 of the procedure above when VDI has again grown too large. Do not make excessively large maximum size Dynamic VDIs to start–this problem will only repeat itself over time.