简体   繁体   English

powershell cmdlet的动态输出类型?

[英]Dynamic output type for powershell cmdlet?

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. 编写cmdlet时,可以在其上指定OutputType属性,该属性告知管道中的下一项可以从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 问题是我的cmdlet实际上是通过反射发射在运行时生成类型,我希望能够公开这些类型以获得剩余链的强类型

OutputType is not a contract so it cannot help enforce strong typing. OutputType不是契约,因此它无法帮助强制执行强类型。 OutputType is a hint that tools like Intellisense take advantage of. OutputType是一个提示,像Intellisense这样的工具可以利用它。 That said, it's still very handy. 这就是说,它仍然非常方便。

It sounds like your cmdlet behaves a little like New-Object or Get-CimInstance. 听起来你的cmdlet行为有点像New-Object或Get-CimInstance。 PowerShell determines the output type from these cmdlets by inspecting their arguments and this capability is not extensible. PowerShell通过检查其参数来确定这些cmdlet的输出类型,并且此功能不可扩展。

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. 如果要生成一组固定的类型,我建议在OutputType中显式列出这些类型 - 您可以在OutputType中将类型指定为字符串,因此如果存在类型则无关紧要。

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. 如果您正在生成用户定义的类型(比如您的cmdlet类似于New-Class),那么即使使用私有反射,我也看不到任何实际的解决方案。 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. 使用私有反射,我很确定你可以更新类型列表,但我认为你不能以对Intellisense有用的方式更新该列表,因为当PowerShell确定管道类型时没有好的可扩展性钩子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM