Skip to main content

Virtualisation is the way of the future, be it for demos or testing or production systems it is the future, and that means VHD files will be everywhere. However VHD files grow and grow and never shrink because of the way they are designed to work. For example if you put a 10Gb file on a VHD, it expands the VHD by 10Gb (for the disk) but if you delete a file the space of the VHD isn't reclaimed automatically.
This is pretty much ok for production systems (your VHDs live on a SAN with lots of disk or they should do for a lot of good reasons).
However if it's on your laptop for training/R&D or sending to customers being able to claim that disk space can be valuable and the advantage is it can be done manually so let me show you how it can be done in Hyper-V.
For this post I have a VHD which contains a MSSQL database (MDF and LDF) file on it, the disk space usage on the VHD for the drive looks like this:

image
So the VHD is supposedly a max of 300Gb and I have never copied that much on to it, and at the moment it contains a simple 53Gb and some change on it. The actual VHD file on my laptop looked like this, using a nice 117Gb of real disk space. So there is at least 64Gb I could get back!

image
The first step in shrinking the disk is to defrag it on the virtual machine, as the shrinking process only cleans space from the end of the disk. So if you have any data at the end like I did (see below) you'll need to (re)move it. Unfortunately as you can see I had an unfortunate "unmovable" piece of data conveniently at he end of the disk. Thankfully it turned out to be the LDF file for the SQL database.

image
So a quick truncate/empty of the LDF file (don't do that in production, but if you want to know how I did it see here) made it a lot easier to defrag the disk (especially) getting the data at the end freed up. Since I didn't have too much free time I skipped the defrag, so just working on the big (now) empty space available before the MDF (blue) file.

image
Step two is to shut down the VM, then go to the settings and go to the disk settings and click edit. This will bring up the disk edit wizard and the keep the first selected option, Compact.

image
This is very cool  because is actually loads the VHD as a disk on host operating system! In fact you can browse it and edit it (I would guess, but that may screw the compact up). This is similar to the VHDMount tool in Virtual Server. I am not sure how to do it manually in Hyper-V yet, because it would be really cool to be able to do that now.

image
After some time, let me rephrase that a significant amount of time, which in my case was a 6 odd hours,  it finished compacting the VHD file to 60Gb less!

image