I've seen (and tried) many ways to skin this cat, but none are quite as effective as I thought and require a number of manual steps. Here is my scenario:
1) I have installed an OS on a Dynamic Virtual Hard Drive via Hyper-V or Boot to VHD on Windows Server 2012 or Windows 8, let's say it takes ~30Gb. 2) I use the VHD, add a lot of files, and then remove them. This expands the VHD to say, ~100Gb.
I want a smooth, simple and reliable operation that does not require prior defragmentation (unless that is a one-step operation), that will recover all the free space on the VM.
My experience in times past is that defragmenting, perhaps zeroing, and then compacting a VHD does not recover all the space and it's quite a messy operation.
As a final option, can I perhaps 'clone' my existing dynamic disk (with the space freed up) to a fresh Dynamic VHD?
I'd be even more pleased if the whole process was able to be scripted via PowerShell.