Shrink HyperV virtual hard disk Win8 / Win2012 with PowerShell

I read this post by Ben (Virtual PC Guy) Armstrong about shrinking a virtual hard disk and thought this should be done with powershell.

So first I have to shrink the partition inside the VM, for this I use the New-CIMSession (instead of powershell remoting and such) and then I shut down the VM and shrink the VHDx file, As someone correctly noted, this shrink of the virtual disk file is only possible when using the new VHDx format.

The VM is part of the same domain as the hyper-V server from which I am running the script, this made it easier to make a cim connection. The VM is also a Win 8 beta cause I need the latest win framework with powershell 3.

As you can see, the disk in my VM is 60 GB and I want to shrink it to the minimum size * 20% (so i get at least some space left 😉

Now I will run my little script and here is what that looks like

# vNiklas Masterblaster shrink
#
# Niklas Akerlund / 2012-05-13

$VM = "Shrink8"

$cim = New-CimSession $VM

$partitionC = Get-Partition -CimSession $cim -DriveLetter C

$newSize = ($partitionC | Get-PartitionSupportedSize).SizeMin*1.20

Resize-Partition -PartitionNumber $partitionC.PartitionNumber -DiskNumber $partitionC.DiskNumber -Size $newSize -CimSession $cim

Get-Volume C -CimSession $cim

$VM = Get-VM $VM

Stop-VM $VM

$hdd = $VM | Get-VMHardDiskDrive

Resize-VHD -Path $hdd.Path -ToMinimumSize

Start-VM $VM

And here you can see the result, a quite simple solution..

Good luck in your shrinking 🙂

Update:  I totally missed that Ben had done a post about doing it with powershell, just after his other post when i was making this post… At least my solution show how to connect to a VM with CIM 🙂