Windows: How To Compact A Dynamic VHD

Making use of dynaminc VHDs or Virtual Hard Disks has the benefit of growing along with the users need. The downside is that even after files are deleted from a dynamic VHD it will remain the same size as if the files where never deleted. This becomes a problem if you make use of multiple VHDs because you are essentially wasting space on files that no longer exist. The solution is to Compact the VHD using Diskpart a tool provided with Windows.

Start Compacting

Open a command line window and type:

diskpart

Select the disk you wish to compact by specifying the drive where the file is located and the path:

select vdisk file=”F:DAT100GB.vhd”

Attach the disk as Read-only:

attach vdisk readonly

And issue the command to compact:

compact vdisk

Depending on the size of the drive the operation may take some. Detach the VHD:

detach vdisk

In my case after compacting a 100GB VHD with 20GB of deleted data the size decreased to 82.2MB, Dynamic VHDs are useful but can also become the reason why disk space is low. If you have any questions leave a comment below.