Original Article: https://community.spiceworks.com/topic/2288371-hyper-v-vhdx-fragmentation


Run these commands in PowerShell and it will defrag and compact properly.

You will have to turn off the VM to run these commands. Change the path name and defrag drive letter to whatever your system assigns.

mount-vhd "D:\VMNAME\Virtual Hard Disks\DISKNAME.vhdx"
defrag e: /h /x
defrag e: /h /k /l
defrag e: /h /x
defrag e: /h /k
dismount-vhd "D:\VMNAME\Virtual Hard Disks\DISKNAME.vhdx"
optimize-vhd "D:\VMNAME\Virtual Hard Disks\DISKNAME.vhdx" -Mode Full