
Compact a Dynamic VHDX with DiskPart
VHDX files can take up a lot of unnecessary disk-space, especially if the disk is used for a lot of writes. A dynamic vdisk expands, but does not automatically compacts again.
Sometimes it is necessary to first defragment the disk. I use PerfectDisk V14 for this, but there are a lot of defragmentation tools around that work just as well. After the VHDX is defragmented and optimized for shrinking, open a command prompt with administrator rights and start DiskPart:
Type the following commands:
- select vdisk file=”<path to the virtual disk>” (quotes are mandatory if there are spaces in the path)
- attach vdisk readonly
- compact vdisk
- detach vdisk
- exit
The disk will now have shrunk to the size that the data on the disk is using (if defragemented properly).
Why compacting a dynamic VHDX matters
A dynamically expanding VHDX grows as data is written to the virtual disk, but deleting files inside the virtual machine does not automatically return that space to the Hyper-V host. Over time, the VHDX can therefore occupy considerably more physical storage than its remaining data requires. Compacting it reclaims unused blocks and reduces the file’s physical size without changing the virtual disk’s configured capacity or deleting its active data. This helps conserve host storage, shorten backup and replication times, and prevent old or heavily used virtual machines from wasting space. Always ensure the virtual machine is shut down, the correct VHDX is selected, and a verified backup is available before performing storage maintenance.



