Compact a VHD file created by Disk Management?

6

1

My computer is running on Windows 7 64-bit. I used Disk Management to create a new VHD file and made it into a new virtual drive. The size of the disk is 8GB. After using about 3GB, I decided to format it. However after formatting the size of the disk is still 3GB.

I tried diskpart to compact this VHD file and I got this error message

Virtual Disk Service error: The requested operation requires that the virtual disk be attached read only.

So, is there any way to compact this VHD file?

Teiv

Posted 2012-10-29T09:12:01.123

Reputation: 779

1Try unmounting the disk before compacting it... – Graham Wager – 2012-10-29T09:14:33.437

Where is that option to unmount the disk? – Teiv – 2012-10-29T09:16:30.107

1Inside Disk Management, right-click the Disk (not the volume) and there should be an Unmount or Eject option in the menu – Graham Wager – 2012-10-29T09:18:13.947

I don't see that option, only "Detach VHD", here is the screenshot http://i.imgur.com/OyH1C.png

– Teiv – 2012-10-29T09:26:24.803

1

That's the one, Detach VHD, then follow the instructions here: http://linhost.info/2011/01/windows-how-to-compact-a-dynamic-vhd/

– Graham Wager – 2012-10-29T09:36:16.890

It worked! Thanks so much for your help but I can't mark your comment as answer. Also is there another faster way not to use diskpart or some kind of automation tool for this? – Teiv – 2012-10-29T09:56:04.283

Happy to help :) I'll post it as an answer in a second, there may be some 3rd party tools out there to automate it but I just tend to use diskpart personally (or Hyper-V Manager on Windows 8/Server) – Graham Wager – 2012-10-29T09:57:50.170

Answers

8

Compacting can't be completed on a VHD that is attached unless it is read-only.

To detach the disk, you need to right-click the VHD disk in Disk Management and select Detach VHD:

Detach VHD

You can then complete the compacting using diskpart from a Command Prompt:

  1. Run diskpart
  2. Select the disk via its path: select vdisk file="<path>"
  3. Attach it as read-only: attach vdisk readonly
  4. Compact it: compact vdisk
  5. Upon completion of the compact, detach it again: detach vdisk

You can then re-attach it via Disk Management in its normal and newly compacted state.

(Reference: http://linhost.info/2011/01/windows-how-to-compact-a-dynamic-vhd/)

Graham Wager

Posted 2012-10-29T09:12:01.123

Reputation: 10 589