How to shrink/compact the size of dynamically expanding VHD/VHDX files with Hyper-V in Windows Server 2012 R2
How to shrink/compact the size of dynamically expanding VHD/VHDX files with Hyper-V in Windows Server 2012 R2
There are different ways to reduce the size of dynamically expanding disk in Hyper-V.
If you won’t to cleanup unnecessary files in the VM (for example Windows Updates, temporary files and more) you can use the cleanup function of the OS in the VM.
You have to install the Desktop Experience feature with the Server Manager or Power Shell:
After that you can use Disk Cleanup.
If the OS of the VM is Windows 8 or Windows Server 2012 and higher, you can now use the hard disk “optimize” feature in Windows to optimize the drive as a preparation to shrink / compact the VM.
Navigate to the properties of the disk in File Explorer and click the Tools tab and the Optimize button.
Start optimizing the drive. After optimization has been finished, shut down the VM and use the Hyper-V Manager or PowerShell to compact the disk of the VM.
Right click the properties of your Hyper-V Host and select Edit Disk from the context menu. Select the disk to compact and click Compact.
Depending on the disk size and the amount of data to compact, the process will take a while.
Compacting disks via PowerShell
To compact every VM installed on the local Hyper-V host you can use the following PowerShell script. It is also possible to compact individual hard disks:
Get-VM | Get-VMHardDiskDrive | Optimize-Vhd
Compacting VM with older OS than Windows 8 / 2012
To reduce the size of a VM there is one way to install the Desktop Experience feature as mentioned earlier in this article.
After Disk Cleanup has been finished, shut down the VM and mount the VM on the Hyper-V parent partition.
Navigate to the VHD/VDHX file in File Explorer and right click the file and select Mount. After hat navigate into the properties of the mounted hard disk file and select Optimize from the Tools tab.
If the optimization process has been finished, dismount (Eject) the hard disk file and compact the VHD/VHDX. This should reduce the size of the virtual hard disk.