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 YOUR VDI FILE BEFORE DOING THIS PROCEDURE!

  1. in guest Windows, run Disk Defragmenter
  2. in guest Windows, in Command Prompt, run
    sdelete -z c:
    
  3. 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.
  4. 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)
  5. 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
  6. in host Linux Terminal:
    cd ~/VirtualBox*/WinXP
    

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

    vboxmanage modifyhd --compact MyFile.vdi
    

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

  7. Observe that the VDI file size has dropped a lot!

Notes

  • 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.

Leave a Comment