One of my favorite VirtualBox features is the “dynamically expanding storage” option, which allows a user to create a virtual hard drive that is only as large as the files it contains. However, when files on a dynamically expanding drive are deleted, the drive doesn’t shrink again. To compact your VDI and reclaim space on your physical hard drive, especially before backing up your disk images, you will need to use a VirtualBox feature that isn’t very well documented: VBoxManage compact.
Synopsis:
1. Defragment virtual disk at least twice
2. Zerofill the VDI’s free space using sdelete.exe (sysinternals)
3. Shut down the VM and run VBoxManage compact on the host OS
4. ????
5. Profit
If you have worked with a “headless” VirtualBox installation, (i.e. command line only) you may already be familiar with the VBoxManage program and its features. There are quite a few, and you need to use it if you want to compact a disk image or clone a VDI hard drive. These are the steps to to compress a VDI file. Before compressing, my VDI was 11.9 GB:
The Process
1. Start the virtual machine with the VDI you wish to compact. Delete all unnecessary files. At this point, I recommend running the Windows Disk Cleanup wizard. It can free up half a gigabyte or more in some cases.
Once you’re finished cleaning up and deleting old files, right click the disk, click Properties > Tools > and the “Defragment Now” button. Click “Defragment.”
Note: Be sure to defragment your disk several times (at least twice)
Once you’re finished defragmenting, go to Microsoft’s Sysinternals Live Site (http://live.sysinternals.com) and download sdelete.exe, the Secure Delete executable, onto your virtual machine. Run it by opening a command prompt (Start > Run, then type cmd, and hit Run) and browsing to the download directory. Then, run it with the -z and -c options set.
|
1 2 3 |
C:>sdelete.exe -z -c c: |
-c is the most important, because it zeroes the free space on your VDI, allowing it to be compacted. It may take a few minutes for sdelete to finish.
When sdelete terminates and returns you to the command prompt, shutdown the virtual machine. When the machine has finished shutting down, open your terminal and run VBoxManage with the following flags:
|
1 2 3 |
$ VBoxManage modifyhd /_full_path_to/disk.vdi compact |
Replace _full_path_to, with the full path to your .vdi file. It should take a few minutes. When VBoxManage finishes, check the size of your file. It should be smaller. In my case, it was almost 6 GB (~ 50%) smaller. I needed to make my images smaller so I could back them up, in preparation for a big upgrade
VBoxManage is a very powerful tool, and it can be used to perform a number of management related tasks, including resizing and cloning disk images. The full documentation for VBoxManage (pdf) can be found on the VirtualBox website.







Nice right up. Doing this right now.