Skip to content

[Question] Advanced functions | Parameter binding by PSTypeName #107

Open
@OCram85

Description

@OCram85

Hi guys,

I recently discovered the possibility to bind a parameter by a custom type name. The common approach seems to be using [PSCustomObject] as parameter type if you don't use classes.

Just for clarify a little example:

function Get-MyAwesomeCustomType {
    [CmdletBinding()]
    [OutputType('ModuleName.Context.Identifier')]
    param()
    $returnObj = [PSCustomObject]@{
        somePropertyKey = 'awesome value'
        foo             = 'bar'
    }
    $returnObj.PsObject.TypeNames.Insert(0, 'ModuleName.Context.Identifier')
    Write-Output $returnObj
}

function Invoke-AwesomeStuff {
    param(
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [PSTypeName('ModuleName.Context.Identifier')]$InputObj
    )

    Write-Host $InputObj.foo
}

My questions here are:

  • Does this scenario of using PSTypeName for parameter binding respect the best practice and common used style guide?
  • It seems to fill the gap for using the PSCustomObjects and still be able to bind it properly. So why is this so rare to find?
  • Is this a newer feature? Was this introduced in v4 or v5?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions