I was recently lurking in Slack and saw that Kirk Munro had posted a tip that I had previously done only with C#. Kirk showed us how to define custom object types by using the [pscustomobject] type accelerator by simply defining a PSTypeName property.

By using PSTypeName as a property and the type as the value like below, we can create custom objects with a specific type.

$widget = [pscustomobject]@{    PSTypeName = 'Widget'    Color = $null    Size = $null}
2016-05-06_20-48-11

You can now see that the object isn't just a PSCustomobject but shows up as the type we just defined. This is also useful when passing these kinds of objects into functions as well.

I can now build a function like this which will only accept the PSType I just declared.

function Get-Something
{
    [CmdletBinding()]
        param
        (
            [Parameter()]
            [ValidateNotNullOrEmpty()]
            [PSTypeName('Widget')]$Widget
        )
    
        $Widget
}

Pretty cool!

Join the Jar Tippers on Patreon

It takes a lot of time to write detailed blog posts like this one. In a single-income family, this blog is one way I depend on to keep the lights on. I'd be eternally grateful if you could become a Patreon patron today!

Become a Patron!