Defining multiple Output Types in a function

Defining an Output Type for a function is a useful way to inform other users or tools about what to expect once the function has been executed.

While doing some research I came across the documentation for the OutputType attribute and noticed that it’s possible to set an Output Type per Parameter Set. You can use the ParameterSetName property in the declaration. For example:

[OutputType('[System.String]', ParameterSetName="A")]
[OutputType('[System.Array]', ParameterSetName="B")]

    [Parameter(Mandatory=$true, Position = 0, ParameterSetName="A")]

    [Parameter(Mandatory=$true, Position=1, ParameterSetName="B")]

The OutputType property of Get-Command reflects each type specified above:

Personally, when designing a function, I always try to ensure that it has a single purpose and will only return a single type. However, in the case where this is unavoidable and you are using Parameter Sets to categorise your parameters this is a neat way to do the same with your Output Types.

Leave a Reply

Your email address will not be published. Required fields are marked *