How to programmatically add a PSCmdlet to a Powershell pipeline?

泪湿孤枕 提交于 2019-12-08 06:45:02

问题


I'd like to programmatically assemble and run a pipeline containing my own PSCmdlet. However, the Pipeline class only allows to add strings and Commands (which are constructed from strings in turn).

var runspace = ...;
var pipeline = runspace.CreatePipeline();
pipeline.AddCommand("Get-Date"); // ok
var myCmdlet = new MyCmdlet();
pipeline.AddCommand(myCmdlet); // Doesn't compile - am I fundamentally 
       // misunderstanding some difference between commands and commandlets?
foreach(var res in pipeline.Invoke()) {...}

I believe that what I'm doing should basically make sense... or is there a different way to do this?


回答1:


Your cmdlet should have a well-defined syntax, based on what you put in the Cmdlet attribute.

For instance, here's the start of where I create my own clear-host cmdlet to replace the built-in clear-host function:

<Cmdlet("clear", "host")> _
 Public Class Clearhost
     Inherits Cmdlet

From the Cmdlet attribute, the syntax for my cmdlet is "clear-host". You should be able to use that (since it's a string) and add it to the pipeline.




回答2:


After searching through other answers and poking around System.Management.Automation in ILSpy, I'm convinced that it is impossible to add Cmdlet instances directly. PowerShell requires you to use strings, which is unfortunate if you just want to drive it from .NET using proper types.



来源:https://stackoverflow.com/questions/5184757/how-to-programmatically-add-a-pscmdlet-to-a-powershell-pipeline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!