Building Custom Object Types with PowerShell and PSTypeName

Adam Bertram

Adam Bertram

Read more posts by this author.

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}
Creating a custom PowerShell object type
Creating a custom PowerShell object type

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!

Subscribe to Adam the Automator

Get the latest posts delivered right to your inbox

Looks like you're offline!