Compact/defrag VirtualBox VDI disk

VirtualBox disks can get out of shape if you expand and reduce them and/or they can get slower over time. Compacting a virtual disk can help, here are the steps:

  1. Inside the VM Guest run the defrag utility or 3rd party defragger if you have one.
  2. Empty the free space to zeros with sysinternals sdelete utility. See From an elevated command prompt run:
     sdelete -c -z c: 

    Now shutdown the VM Guest

  3. On the host computer, run the “VboxManage modifyhd” command to compact the disk. For example if your disk image is located in /home/keith/VMGuests/win8.1/win8.1hd.vdi run this:
     $ VBoxManage modifyhd /home/keith/VMGuests/win8.1/win8.1hd.vdi --compact