# Compact VirtualBox VDI size

I created a dynamically growing VirtualBox VDI and wanted to shrink its size after a long time of use. I briefly searched for the solution and it seems that the steps to do so are:

1. Zero the free space (by creating a large file filled with zeros).
2. Run vboxmanage modifyhd <VDI> --compact.

My problem here is that the VDI size (seen in the guest) is much larger than that of the partition where the VDI resides (e.g. 2TB VDI on a 320GB partition). Is the above method still doable in this case? If not, are there any other possible solutions?

Also, if VDI fails to support such an allocation scheme, will any other virtual disk formats do?

• the vboxmanage tool cannot shrink virtual box's virtual hdds. You would have to convert the file, use a different tool, then convert it back. – Ramhound May 8 '15 at 11:04
• Is there any tool which can give me a shrinked VDI without expanding it to its maximum size? – Cyker May 9 '15 at 3:34

You can let VirtualBox automatically discard the unused blocks from the image when it receives the TRIM command (which is supported since VirtualBox 4.2) from the OS

• Storage: implemented support for discarding unused image blocks through TRIM for SATA and IDE and UNMAP for SCSI when using VDI images

You'll need to use the --nonrotational on and --discard on options to set the disk image settings, something like

VBoxManage storageattach <VM name> --storagectl "SATA" --port 1 --device 0 --nonrotational on --discard on --medium path\to\file.vdi --type hdd

• --discard

Enables the auto-discard feature for a virtual hard disks. This specifies that a VDI image will be shrunk in response to the trim command from the guest OS. The following requirements must be met:

• The disk format must be VDI.
• The size of the cleared area must be at least 1 MB.
• Oracle VM VirtualBox will only trim whole 1 MB blocks. The VDIs themselves are organized into 1 MB blocks, so this will only work if the space being trimmed is at least a 1 MB contiguous block at a 1 MB boundary. On Windows, occasional defragmentation with defrag.exe /D, or on Linux running btrfs filesystem defrag as a background cron job may be beneficial.

You can also open the *.vbox configuration file and add discard="true" nonrotational="true" to the <AttachedDevice> tag

<AttachedDevice nonrotational="true" discard="true" type="HardDisk" port="1" device="0">
</AttachedDevice>


The vboxmanage modifyhd (or modifymedium on more recent vbox versions) can compact the vdi file. A dynamic disk can be created as you mention like 2TB in a 350Gb partition, this kind of disk increases its size when you use more space in the virtual machine until there is no available space on the physical disk. Performing a compact doesn't get the full size of the vdi, you need to follow this process to compact the vdi file as the size you can see on the guest: