When we try to compact dynamically expanding VHD or VHDX we have to do few things if we want reach good results.
First we need to know how file system is working. It is important to know that when we delete a file or just a part of the file, those data are not really deleted, you just remove a pointer to that sector. This is important because the compact operation will just remove the free space and simply deleting the file will not free the space on VHD file.
For this reasons you have to prepare VHD before you can compact it. To prepare virtual disk for this operation, three steps are important:
- Empty Recycle bin – if you have files in Recycle bin it is best practice to delete them before compacting disk as they need space like any other file.
- Defrag VHD – it is recommended also to defrag the disk for getting best results. This will also speed up your work with VHD.
- Write zeros to free space – writing zeros on free space you will remove all “deleted” data, so this is a really important step that will free your space.
To write down zeros you need external application as there is no build in application to do it. I am using Rusinovich’s SDELETE (https://support.microsoft.com/en-us/kb/2786067). The usage is very simple; you have just to run sdelete from administrative command prompt with Z switch. For example, if you want to free space on D drive you have to run a command in this way:
Sdelete.exe -z d:
With this command you will free space and now you are ready to compact VHD form Hyper-V manager or PowerShell. Using this steps, you will really decrease a space used by VHD. .
One comment found on “How to compact VHD or VHDX”
I have found that it is pretty easy to compact vdisks from within a command prompt using diskpart. I prefer the method below to using powershell, and I like that you don’t need to shrink partitions in your vdisk and or zero out unused disk space for it to work.
From an elevated command prompt type:
select vdisk file=”C:\Hyper-V\sampledrive.vhdx”
attach vdisk readonly
This is how I reduced the size of my Master Image from 24GB to 15GB and it takes seconds to complete. The article I published on compacting vdisks can be found at: https://www.alaskacomputerguy.com/category/howto/how-to-compact-vhdx