0

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
}
lit
  • 14,456
  • 10
  • 65
  • 119
  • 4
    You have `[OutputType ???]` inside the param block? It should be outside together with the cmdletbinding decoration – Santiago Squarzon Jun 25 '23 at 03:07
  • @SantiagoSquarzon, ok, I will put it outside. The real question is what should replace `???` to represent the `[PSCustomObject]` that will be output? – lit Jun 25 '23 at 12:23
  • I don't understand why you have a person class yet you want to output a pscustomobject. Doesn't make sense – Santiago Squarzon Jun 25 '23 at 13:22

1 Answers1

1

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

Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37
  • Can this be done without a `function` as the question asks? Can a plain .ps1 script produce and `OutputType` of the user's creation? Would `Add-Type` be of any use? – lit Jun 25 '23 at 18:22
  • @lit if the class is loaded beforehand I dont see why not. `Add-Type` has nothing to do with this, a PowerShell class is compiled at runtime – Santiago Squarzon Jun 25 '23 at 18:25
  • How would the class be loaded beforehand? Built-in types such as `[string]` and `[FileInfo]` are loaded beforehand. What needs to be done to get this `[Person]` type loaded beforehand? Must this come from an `Assembly`? It seems that the `Assembly` would need to be loaded into the session before the PowerShell instance starts interpreting the .ps1 script. I have not yet found an example on the net. Can you suggest an example? – lit Jun 25 '23 at 19:56
  • @lit the graceful way to do it is with a module, else, one of the workarounds named in https://stackoverflow.com/questions/42837447/powershell-unable-to-find-type-when-using-ps-5-classes – Santiago Squarzon Jun 25 '23 at 20:00