Shrinking disks on your Hyper-V guests
A few of my guests run on SSD drives. Occasionally I reclaim diskspace by defragmenting and compacting the VHD;s. I have managed to free up to 20GB diskspace on a single guest, which is pretty much SSD wise. However, first of all, you should consider before putting R/W intense operations, such as VMs, on your SSD;s.
Since this is a process that will take quite some time I wanted to make it as automated as possible.
1. Defrag with Raxco perfect disk. This script is run remotely on the target machines. Errorhandling is omitted for readability.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
REM Verify PDCmd functionality "c:\Program Files\Raxco\PerfectDisk\PDCmd.exe" > c:\temp\raxco.txt REM Prepare for shrink "c:\Program Files\Raxco\PerfectDisk\PDCmd.exe" /prep /alldrives /w REM Online defrag "c:\Program Files\Raxco\PerfectDisk\PDCmd.exe" /dol /alldrives /w REM Zerofill "c:\Program Files\Raxco\PerfectDisk\PDCmd.exe" /z /alldrives /w |
2. Compact VHD:s. Run in powershell on the Host. Make sure the actual VM is turned off.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
Import-Module Hyper-V $vm_name = 'SERVERNAME' $get_vhds = get-vm $vm_name | select -expand HardDrives | get-vhd |select path foreach ($vhd in $get_vhds) { $vhd = $vhd.path.tostring() Mount-VHD -Path $vhd -readonly Optimize-VHD -Path $vhd -mode quick Optimize-VHD -Path $vhd -mode full DisMount-VHD -Path $vhd } |