Extending PowerShell with Custom Property Sets

If you’ve been following along on the blog recently you’ve read about my use of PowerShell type extensions. This is a way of adding new properties to things I use all the time. The goal is to save typing and get what I need with minimal effort. You can also take this a step further by creating your own property sets.

You probably didn’t know it but PowerShell already uses property sets. Here’s an example you can try yourself.

image

Where did that come from? Pipe Get-Process to Get-Member and see for yourself.

image

A property set is a shortcut way of selecting a subset of properties. You can also define property sets. Let’s take my Hyper-V extensions that allow me to run a command like this:

image

I may want to see this group of properties often. But I clearly don’t want to type this all the time. You can define a new property set with the Update-TypeData cmdlet, but it will require a little more effort. Unfortunately, there are no easy parameters to use. Instead you need to create a ps1xml file like this:

Hopefully this shouldn’t be too difficult to read. I’m defining a property set member for the VirtualMachine type with a name of PSConfig.  This property set will use the referenced property names. You can add definitions for other types in the same XML file but I’m not so I named this file MyHyperV.types.ps1xml. The name doesn’t really matter but the pattern is to use types.ps1xml as part of the file name.

To load this file I add this line to my PowerShell profile script.

I’m not defining anything that conflicts with the out-of-the-box definitions so it doesn’t matter if I prepend or append. Now my life is much easier.

image

I can see the new definition with Get-Member.

image

The XML can be a little daunting at first but once you have the outline it should be a simple matter of cutting and pasting. Just remember to watch your tags and case.

Does this look like something you’d use?

5 thoughts on “Extending PowerShell with Custom Property Sets

  1. It actually looks very handy, and i might consider using it where useful.

    But what i use a lot are calculated properties, which i presume cannot be used in this format?

    • I believe that is the case. You would first define the property extensions as I did in a previous post. Then you can define the property set using those new properties.

  2. I see referenced properties, which I assume, only includes existing properties. Can new custom properties be defined in the psconfig file?

Leave a Reply

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