How to invoke script-module cmdlet from a binary cmdlet?

Viewed 249

I am writing a Powershell cmdlet in C# by inheriting from PSCmdlet. This is part of a powershell module which contains both binary and script components.

I want to be able to invoke a script module cmdlet from within my binary cmdlet.

I've worked out that inheriting from PSCmdlet gives me access to a lot more of Powershell's guts, and I have looked specifically at InvokeCommand.GetCmdlet() and InvokeCommand.GetCommand() but these both seem to return CommandInfo objects which don't appear to have a method to invoke them.

Am I supposed to call InvokeCommand.InvokeScript() to call my cmdlets? If so how/are CommandInfo objects supposed to be used to help?

1 Answers

Likely InvokeScript is what you want because you want to execute a script. Now, you likely had issues because you would use it more like

InvokeCommand.InvokeScript("Get-MyCmdlet -ParameterName value");

That being said, the real answer to your question is that you need a PowerShell object that represents the interpreter.

var ps = PowerShell.Create();
ps.AddCommand(InvokeCommand.GetCmdlet("Get-MyCmdlet"));
ps.AddParameter("ParameterName", "value");

var output = ps.Invoke();

The interpreter uses CommandInfo (and AddCommand has an overload with a string that under-the-hood would create one) for its Reflection work to interpret whatever you want.

Related