Shrinking a VHD in Windows 8 – fast!

A couple of days ago I talked about how it was much easier to shrink a virtual hard disk in Windows 8.  But after writing that blog post – I spent some time playing around with PowerShell and found that there was an even better option.

Instead of logging into a running virtual machine, doing some work, shutting it down and completing the operation.  You can do everything from PowerShell in Hyper-V if the virtual machine is shutdown first.

The process that I figured out is as follows:

  • get-vm <vmname> | select ID | get-vhd | select path
    • This command will get you the virtual hard disk path and file name for each virtual hard disk in the virtual machine. Obviously you can skip this if you already know it.
  • mount-vhd <vhdname> –passthru | get-disk | get-partition | get-volume
    • This will mount the virtual hard disk in the management operating system, and let you know the drive letter that was assigned to it.
  • resize-partition –driveletter <driveletter> –size <newsize>
    • This will resize the partition inside the virtual hard disk
  • dismount-vhd <vhdname>
    • Dismount the virtual hard disk after shrinking the partition
  • resize-vhd <vhdname> –ToMinimumSize
    • Now shrink the virtual hard disk to match the new size

Here is a screenshot of me resizing a virtual hard disk from 50GB to 30GB on a virtual machine:

PowerShell resize

This whole process took under a minute and was completed without needing to start the virtual machine.

Cheers,
Ben