Question

When writing a cmdlet you can specify the OutputType attribute on it which tells the next item in the pipeline the types you can emit from your cmdlet. But, is there a way to dynamically specify that? Attributes don't let you do dynamic returns, since they have to be compile time constants (unless there is some magic around that)

The issue is that my cmdlet is actually generating types at runtime via reflection emit, and I'd like to be able to expose those types to get strong typing for the remaining chain

Was it helpful?

Solution

OutputType is not a contract so it cannot help enforce strong typing. OutputType is a hint that tools like Intellisense take advantage of. That said, it's still very handy.

It sounds like your cmdlet behaves a little like New-Object or Get-CimInstance. PowerShell determines the output type from these cmdlets by inspecting their arguments and this capability is not extensible.

If you are generating a fixed set of types, I would suggest listing those types explicitly in OutputType - you can specify types as strings in OutputType so it doesn't matter if the types exist.

If you are generating user defined types (say your cmdlet is something like New-Class), then I don't see any practical solution, even using private reflection. With private reflection, I'm pretty sure you can update the list of types, but I don't think you could update that list in way that's useful for Intellisense because there is no good extensibility hook when PowerShell is determining the type of a pipeline.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top