Microsofts VHDs, short for Virtual Hard Disk, offer a way to create a filesystem inside a file and mount that in a windows drive. It works a little bit like loopback devices, which you may know from Linux. Windows offers two ways to create these, either statically or dynamically sized. If you choose to create a dynamically sized VHD, the VHD file grows if you store data in it. If you delete data from the drive, it doesn’t shrink. That’s bad if you store temporary data on your VHD. It’s slowly eating all your hard drive storage.
I googled a little bit and found a solution to shrink VHDs here. Unfortunately this is a Powershell script which has to be run as administrator. If you need to shrink the VHD often, starting the Powershell as administrator and entering the path to the VHD file will annoy you very soon.
I’ve written a small tool in C# which uses UAC to start as Administrator and accepts the path to the VHD as first commandline argument. Now you can just drag’n’drop the VHD file onto the exe file, Windows asks you if you want to grant the tool Administrator rights and the VHD will be compacted.
The tool will perform the following steps:
- Attach the VHD to a free drive letter
- Run the defragmentation tool, which compacts the data on the drive
- Detach the VHD and reattach it as readonly
- Compact the VHD
- Detach the VHD
After running this tool, the VHD is using the minimum necessary space.
You can download the tool here. Have fun.