How to create a type to specify as the `OutputType`?

96 views Asked by At

The information at https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions_outputtypeattribute?view=powershell-7.3 is helpful. Also, https://stackoverflow.com/a/57478857/447901 is helpful. But, the only examples given are predefined PowerShell types. I need to define my own object, not just a simple [string].

[CmdletBinding()]
param (
    [OutputType ???]
)

[PSCustomObject]@{
    FirstName = 'Bill'
    LastName = 'Smith'
}

I tried creating a class, but could not get that to work.

class Person {
    [string]$FirstName
    [string]$LastName
}
1

There are 1 answers

4
Santiago Squarzon On

If you're declaring a Person then doing [OutputType([pscustomobject])] makes no sense, you should be returning an instance of that class instead. Declaring that your output type will be pscustomobject is the same as not having any declared output type at all since these objects can have any structure.

class Person {
    [string] $FirstName
    [string] $LastName
}

function Test {
    [CmdletBinding()]
    [OutputType([Person])]
    param (
        $FirstName,
        $LastName
    )

    [Person]@{
        FirstName = 'Bill'
        LastName  = 'Smith'
    }
}

Much better to make the promise to return an instance of your class, then the completers would work properly:

thing