Effective VHDX compacting with HYPER-V 2012 and networked storage

There are a lot of instructions out on the internet which lead you through some compacting routine, with varying success. This usually amounts to stopping the VM/VDI and running the disk edit function from the HYPER-V console. In many cases, and especially if you are using networked storage, you will find that most of the time the “compacted” size of the disk is an exact match of the size before compacting. Or in other words: nothing happened. The most effective way to perform compacting with surefire results is using diskpart on a locally mounted VHDX file. This is in _addition_ to the usual advice to defrag and zero out the unused space. This makes the full procedure:

  • De-fragment the disk, preferably with a defragmenter that also does as much compacting as possible, for example defraggler.
  • Zero out the unused space, so it will be reclaimable. (using sdelete -z -r from sysinternals is an excellent choice here)
  • Down the virtual machine
  • start diskpart
  • Mount the disk with: select vdisk file=”x:\yourpath\yourdrive.vhdx”
  • Run compacting: compact vdisk

This procedure bypasses all kinds of permissions and locking problems you may run into, and will regain the maximum reclaimable unused space. This may still be not equal to the actual usage inside the VM/VDI, because MFT and page file segments often get in the way. Depending on your needs this may not be all bad because reducing a VHDX to its absolute bare minimum will in most cases cause immediate growth on use of the VM/VDI which will increase fragmentation on the host.