Recently, I had a need to shrink a VHD file. Ater running the Resize-VHD command with PowerShell, I realized that it would not work unless the Virtual Machine Management service was installed and running. Instead of performing a Hyper-V install to get this feature, a little research led to diskpart. It turns out that it can also compact/shrink VHD files to free up unused space.
Let’s get started…
Open a command line window and type:
Select the disk you wish to compact by specifying the drive where the file is located including the path:
select vdisk file="F:\DAT100GB.vhd"
Attach the disk as read-only:
attach vdisk readonly
Next issue the following command to compact:
Depending on the size of the drive the operation may take some time.
Detach the VHD:
In my case after compacting a 170GB VHD with 80GB of deleted data the size decreased to 76GB in about 8 minutes (as more than what was deleted could be compacted).