PowerShell: Custom Types, Type conversion and ETS

Before we get into the how, here is why you should care about this!  Consider the following oversimplified function.

First off we need to load our custom types:

Now let try and use this function:

While that’s not that bad, consider the following, it could look like this.

Now I really don’t want to get into which one you should be using.  I prefer instead to focus on how to enable either one!

First things first we’re going to have to get a little dirty with some C# (Again I’m not a developer so if anyone knows a better way to do this I’m all ears.) and create a type converter.

I told you we needed to get a little dirty!  Now that we’ve implemented a type converter that knows how to convert a string to a GetAdmin.Net object.  Now we need to inform PowerShell of our work.  This is accomplished via the a type formatting file.

Next import your new type definition file, and try it out!

Hope that was helpful, know a better way?

~Glenn

4 thoughts on “PowerShell: Custom Types, Type conversion and ETS

  1. Great post!

    One question, why don’t you treat the netmask as a System.Net.IPAddress as well ?
    Would give you validation and avoid a netmask like “345.768.999.876”

    • Thank you,

      I modified some code from PoshOnTap for the purpose of this post, and well… I never thought about it. I looked for a .net type that was netmask, but couldn’t find one. As I think about it there isn’t any reason I couldn’t have casted netmask as an IPAddress as well! In my source code I used a regex to validate the input on netmask, but I removed it for simplicity. I am going to have to play with it some more b/c that could be a very elegant solution.

      As a side the real advantage to casting to IPAddress is the flexibility. [System.Net.IPAddress] is aware of both IPv4 and IPv6! IPv6 being the real pain as the shorthand makes “manual” validation a real pain.

  2. Thanks for article. AFAIK there is another method to convert parameters – using [Transform()] in parameter section of function. In this case you can write only POSH code without need to C#’ing. But it brings some issues with binding piped parameters.

Leave a Reply