In a previous article, I demonstrated how you could use PowerShell to test the health of a Hyper-V virtual machine’s disk files. If you skipped that article, take a moment to read it, otherwise what I’m going to cover in this article might be confusing. The goal is to simplify typing or limit the amount of how much I have to type. I have a working script block that will give me a Boolean value on the existence of the VM’s vhd and vhdx files.
This is essentially the same code that I used in my previous article. Although if you look closely, you'll see I am using $this instead of $_. That's because I intend to use this script block with Add-Member to create a custom property. Specifically, I am going to create a script property that will use the script block to grab the current value. In this situation, $this refers to the current object in the pipeline.
As an added benefit, the new property is now part of the virtual machine object. Stated differently, I can use this property whenever I want, and I don't need to use Add-Member again.
This property will persist for the length of my PowerShell session. For something a bit more permanent, I can update the type configuration file and define my custom property. First, I need to know the type name of the Hyper-V virtual machine object. This is the same information that you would see piping a VM to Get-Member. Because I want my new property to exist every time I start PowerShell, I'll copy and paste my script block and this command into my profile script.
The Update-TypeData cmdlet will extend the definition of the virtual machine object with my new property, which I can immediately verify with Get-Member. This property is ready to use, but I'll have to specify it. And while I'm at it, I think I'll add a custom property to give me the full path to the virtual machine's XML configuration file, which is something else I demonstrated in the previous article.
But why stop now? Let's define a property that automatically expands the paths for all the disk files.
Remember that you have to specify the property to see it, because it won't be part of any default view. As luck would have it, you can create your own custom views with Update-FormatData. However, your head might be spinning a bit from everything I've showed you, so I'll save that discussion for another article.