问题
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