Compacting all your Hyper-V Disks in one script

So I’ve got a good size lab that I run off of my laptop. It’s about 20 Hyper-V VMs, all running something or other System Center, or just acting as a generic client computer to give my SCCM/SCSM environment some actual real data to work with. It’s awesome to have handy (when it isn’t broken!) but it takes up a lot of space, even on my 500GB SSD.

I had a dream last night about SMA and decided it was time to stand up an SMA server in my lab environment. So, this morning, I woke up nice and fresh and logged in to my laptop ready to create a new VM, only to be stopped mid-creation when I ran out of space. Ugh.

Now I know that I *should* have tons of space left, but that it’s all eaten up from when I was installing the entire lab months ago. I’d drag ISO’s around and copy files into VM’s, all of which take up space, and then that space was never reclaimed (I’m using dynamic disk sizing in Hyper-V). I should have just mounted all those ISO’s over the network, but I’m not that smart before a few cups of tea.

Anyway, as I poked around the Hyper-V management interface, I realized that it would be way more clicks than I was interested in doing this early in the morning. So, in another instance of working smart, not hard, I decided to craft a PowerShell script that would do it all for me!

You can find the very latest version here!

Here’s the whole code, though it may be out of date compared to what you find at the link above. Just copy it into the PowerShell ISE or into a PowerShell script file (.ps1), make sure your execution level is set to allow it, and then let it ride!

 

This will get your VM’s, do some nifty work on them, and reclaim your space via disk compaction!

Hopefully it helps someone out there save some time 🙂