Compacting (reducing maximum size of) VDI files for VirtualBox

One might pick a large maximum dynamic disk size for a VirtualBox guest OS, not realizing that even if one uses a small portion of that maximum size, the guest OS (especially Windows) will spread itself out, so that say a 10GB Windows XP NTFS image will consume say 30+GB of your host OS (assuming you set the maximum dynamic size >30GB).

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

BACKUP YOUR VDI FILE BEFORE DOING THIS PROCEDURE!

  1. in guest Windows XP, run Disk Defragmenter
  2. in guest Windows XP, in Command Prompt, run
    sdelete -z c:\ which can be downloaded fromĀ http://technet.microsoft.com/en-us/sysinternals/bb897443.aspx
  3. shutdown guest Windows XP, and “insert” the Gparted ISO file (obtained from http://gparted.sourceforge.net/ ). You do this by right-clicking the CD icon at the bottom of the guest OS VirtualBox window and selecting your ISO file.
  4. Resize your guest Windows XP partition so that you have only say 8GB free (e.g. original partition 40GB, only 10GB used–>resize to 18GB)
  5. reboot guest Windows XP, removing the Gparted ISO file from VirtualBox. you will see Windows XP automatically runs CheckDisk–this is normal. You will need to reboot guest Windows XP once more, then shutdown guest Windows XP
  6. in host Linux, in Terminal type 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. Now you’ll see in Linux that the size of your VDI file has dropped a lot! Nice!

 

Note: for future reference, when you Defragment in guest Windows XP, this actually makes your host VDI file INCREASE in size by the amount of bytes that were moved to defragment!

To fix this, repeat steps 1,2, and 6 of the procedure above when you find your VDI has grown to an annoying size.

The take-away point is, do not make large maximum size Dynamic VDIs to start–this problem will only repeat itself over time.