How to decrease the size of a VHD file/VHDX

This post is, in some ways, a continuation of yesterday's post.

After they solved the problem of the Defragmenter, I discovered that I still couldn't lower my VHD. No matter what I did, the size remains in 127 GB.

Until I discovered the solution to the problem.

Even defragmenting the disk (running the Defrag inside the VM), shutting down the VM and using Compact command of Hyper-V, no point. The size remained the same.

The solution is to forget the Hyper-V and go straight to whoever solves: the command line Smile

Step 1: Optimize the virtual disk

Open a command prompt and type:

DiskPart

Select vdisk file = "c:seuarquivo.vhd"
attach vdisk
list volume

At this point, DISKPART will list the mounted volumes on your computer. The VHD that you just set up should be the last volume. Check in your case what is the letter assigned to your VHD and write it down.

Virtual disk mounted on the host. Note that in this example the volume is the g:
Virtual disk mounted on the host. Note that in this example the volume is the g:

Now you need to defragment the disk. First type exit to leave the DISKPART. Next, type the following command:

Defrag g:/o/v

Where g: corresponds to the drive that you noted in the previous step.

Step 2: Compress the virtual disk

Now let's finish the process in DISKPART. Basically what we do is:

  • Unmount the VHD (in read-write mode);
  • Reassemble the VHD in read-only mode;
  • Compact the VHD;
  • Unmount the VHD.

Back to our elevated prompt, type:

DiskPart

Detach disk

Select vdisk file = "c:seuarquivo.vhd"
attach vdisk readonly
Compact vdisk
exit

Presto! Now our VHD, which previously refused to get out of 127 GB, arrived at the "correct" size:

image
376

 

A hug,
Igor

Author: Igor Abade

Igor Abade V. Leite ([email protected]) is a Visual Studio ALM MVP (Microsoft Most Valuable Professional) since 2006. Speaker at various Software Development community events (TechEd Brasil, The Developers’ Conference, DevOps Summit Brasil, Agile Brazil, Visual Studio Summit, QCON among others), has also written articles in magazines and websites such as MSDN Brazil. Since March/2011 is one of the owners of Lambda3, a Brazilian consulting company specialized in ALM, software development and training. Visit his blog about VS ALM at http://www.tshooter.com.br/ and follow him on Twitter @igorabade.

Leave your comment!