Compacting Virtual Machine disks

3rd June 2014

2 min read

I have been using Microsoft Virtual PC (later Hyper-V in Windows 8) and Oracle’s VirtualBox for many years for running older versions of Windows or Linux for testing & experimenting. Recently I am preferring VirtualBox over Hyper-V for use in my Work PC due to its ease of use, especially clipboard integration and shared folders between Host & Guest OSes. Hyper-V though offering more capabilities its complicated for my simple “client” guest OS needs, feels like driving a Military tanker to shop at local grocery store. In my Home PC (iMac) I love using Parallels, which I think is the best virtualization client out there.

With any of these virtualization engines, the virtual disk (VHD or VHDX or VDI) files tend to fatten in size in the Host OS over a period. In the past I have spent money in buying Invirtus vOptimizer (latter owned by Quest which is a Dell company now) for compacting these files. For example a Windows 7 image (just Windows OS, Office 2010 & Firefox) in VirtualBox in my Work PC was 51GB, similar image in Parallels in my iMac was 80GB (this had snapshots). This time around instead of buying vOptimizer I did some research and found a DiY method which was fairly simple.

Step 1: Run Windows Defrag in the Guest OS, either from command line or start menu. I prefer the command line method with the following command

defrag /C /X /U

Step 2: Download and run sDelete utility free from Sysinternals suite (just the single tool is available too). Run the below Command from command line, which basically puts zero over all free space which helps in later compressing by the virtualization engine.

sdelete -z

Step 3 for Virtual Box: Run the below command from the directory where virtual box is installed (which in my Windows 8 x64 PC is C:\Program Files\Oracle\VirtualBox)

VBoxManage.exe modifyhd virtualdisk.vdi --compact

here virtualdisk.vdi is the full path the virtual disk where ever you have kept it & –compact parameter for modifyhd command does the actual compacting of free space.