Extending Hyper-V with PowerShell

Lately I’ve been writing about my use of PowerShell type extensions as a way to get more done quickly. Or at least give me the information I want with minimal effort. I use Hyper-V a great deal and the Hyper-V cmdlets are invaluable. And while a command like Get-VM provides a lot of information, I always seem to want more so I thought I’d share with you my Hyper-V related type extensions. Even if you don’t need or use Hyper-V, you might find my techniques useful.

The object type for a Hyper-V virtual machine is Microsoft.HyperV.PowerShell.VirtualMachine which you can get easily enough by running Get-VM and piping it to Get-Member. Using Update-TypeData, there are a number of script properties I want to define. These are properties where the value is calculated by a PowerShell script block. For example, I want to be able to quickly see if a virtual machine is missing any of its configured disk files. I could run a command like this:

image

But if I want this information often, that’s too much typing. So instead I can create a script property with this script block. This version takes into account that the VM might have multiple disks, one or more of which might be missing.

On a related note, I’d like to know how much disk space the virtual machine is consuming.

I also like to know the path to the configuration file. This will be a vmcx file with a file name that matches the virtual machine’s ID.

In order to define these, and a few others, I use code like this in my PowerShell profile script.

I define a hashtable where the key will be the property name and the value is the scriptblock I will use.

Next I define a hashtable of parameters that I will splat with Update-TypeData.

The last step is to enumerate the extensions and update type data.

By using hash tables, my code organized and easier to read.

image

And now I can run commands like this:

image

I love that PowerShell provides the flexibility to meet my needs. As always, comments and feedback are welcome.

Leave a Reply

Your email address will not be published. Required fields are marked *