There are many ways to compact a VHDx file. It can be done using SCVMM, Hyper-V manager or even diskpart.
In my situation the compact option doesn’t reduce the size, it was even bigger than before the compact.
I’ve tried to defragment the disk, migrate it or even clean it up inside / without any result.
The only way to get this job done is writing zero’s on the empty space.
This can be done with the tool SDelete, created by Mark Russinovich. The tool zeroes the empty space within the VHDx file.
Before running the tool delete al the un-needed and temporary files.
Sam Boutros created a nice little PowerShell function to get this job done. The package with SDelete and the script can be downloaded HERE.
Example script function parameters:
Compact-VHDX -VHDXPath D:\Dynamic1.vhdx -SDelete .\sdelete.exe
After running the tool the compact action will reduce the space.
Since Windows 2012 Microsoft has the new TRIM/UNMAP command founded, this works only when the Underlying storage supports this.