How to compact Linux VM vhd size in Microsoft Hyper-V

Download PDF


In time Windows and Linux virtual machines running on Hyper-V virtualisation platform will grow in size even if the large part has been freed up within the virtual machine itself. This is because Hyper-V is not smart enough to auto compact the vhd (virtual hard disk) on the fly – to recognise real space usage within the VM. With Windows VM’s this is done very easy by using Edit>Compact options within the VM settings. However, with Linux VM this is not as straight forward.

 In this case I have used CentOS 6.5 running cPanel on a dynamically expanding .VHD (total size 1.5TB)


The first thing you need to do is to zero out the free space within your linux VM. That means, the rest of the free space will be filled with zeros. Type the following command in your linux box (via ssh or hyper-v console)

cat /dev/zero > zero.dat ; sync ; sleep 1 ; sync ; rm -f zero.dat

This command will create a zero.dat file as big as the available free space and then delete it. It may take a while to finish depending on the size assigned.

After the command has finished it will show no more disk space message.


– .VHD file on the host will not grow in size to it’s maximum if you execute this command, it only grows to the maximum within the virtual machine. (in case you have no space for it to grow on Hyper-V host)

– make sure you run this command on a Linux partition that contains the biggest amount of disk space assigned, see my example:

/tmp /var/tmp 4% (140,592 of 4,128,448)
/dev/sda1 /boot 20% (93,976 of 495,844)
/dev/mapper/vg_centos65cp-lv_home /home 5% (76,409,648 of 1,529,194,928)
/dev/mapper/vg_centos65cp-lv_root / 30% (14,663,896 of 51,606,140)
/usr/tmpDSK /tmp 4% (140,592 of 4,128,448)

So in this case you would first switch to home partition because it is the biggest one:

centos>cd /home

centos>cat /dev/zero > zero.dat ; sync ; sleep 1 ; sync ; rm -f zero.dat

If you do it in root partition it will only fill up to it’s maximum which in my case is only 50GB.



Open Hyper-V Manager and shut down the VM first. Then open settings of the VM, select the VHD disk and then edit.

Select the compact option > Next > Finish.




Depending on the VHD file current size, it could take several hours. After it has finished, your VHD file should be smaller.

My VHD file was 460GB, after compacting it, 115GB. 

Any questions feel free to ask!

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply