Sean's Musings as a Service

Sean's Musings as a Service

Compacting Windows VirtualBox virtual disks

  • Published:
  • categories: virtualization
  • tags: compact, vboxmanage, vdi, virtualbox, virtualization

Common problem that everyone using desktop virtualization has, you setup a basic image, install your basic software but you want to share it and you realize that your basic appliance/image is 15G, boo!

Assuming that you pick dynamically allocate space, then you don’t pay for the full virtual size up front. So everytime you use blocks on the virtual filesystem they get allocated in the corresponding virtual disk file(s).

Out of the box Windows VirtualBox ships a command VBoxManage Documentation1 that provides access to some nifty things to work with your disks. Turns out something simple like this will work, but if you have some more time you can usually do better 2:

VBoxManage modifyhd disk1.vdi --compact

The core problem is there may be files that you have deleted but not rather than actually delete them the operating systems simple stops pointing at them and leaves them on disk to be over-written later. Good for your performance, you don’t pay for them to be zero’d out, bad for virtual disks since outside of the OS itself the virtual disk management tools still think that those blocks are being used and will not be compacted away.

Now to deal with this, first things first, for a non journaling filesystem aka NTFS we suffer from defragmentation so it is a good practice to perform the defragmentation on the drive first, to get everything nicely lined up on the virtual disk. Next enter the Sysinternals SDelete3 command. This little gem will actually offer you a few nice options besides the primary secure delete functionality. Here we are only interested in two options, 1 is -c to clean up free space and -z to zero it out.

usage: sdelete [-p passes] [-s] [-q] <file or directory> ...
       sdelete [-p passes] [-z|-c] [drive letter] ...
   -a         Remove Read-Only attribute
   -c         Clean free space
   -p passes  Specifies number of overwrite passes (default is 1)
   -q         Don't print errors (Quiet)
   -s or -r   Recurse subdirectories
   -z         Zero free space (good for virtual disk optimization)
</file>

So we run the following commands: (N.B. Using the -c actually increases the size of the virtual disk file to fill out the maximum size specified for the disk while it attempts to do the cleanup, so if you do not have the temporary space to use, skip that option and just use -z)

c:\ SDelete.exe -c -z

This will run for a while, so take a break and check back on that later. When it completes we are ready to run our VBoxManage *.vdi --compact command again and watch the unused space melt away just like I said in the infommercial…

Good luck!

Reference: