I need to execute Powershell script containing my custom Commandlets ( exist in different assembly) from C#. I tried following approach but it just invokes the commandlet only once and that's it, while in the script that commandlet is written more than once.
Get-MyParameter myTasks
Start-Process notepad.exe
Get-MyParameter myTasks
Get-MyParameter myTasks
Get-MyParameter myTasks
While, MyParameter is written in different assembly. Tried Code is :
var powerShellInstance = PowerShell.Create();
powerShellInstance.Runspace = runSpace;
var command = new Command("Import-Module");
command.Parameters.Add("Assembly", Assembly.LoadFrom(@"..\CommandLets\bin\Debug\Commandlets.dll"));
powerShellInstance.Commands.AddCommand(command);
powerShellInstance.Invoke();
powerShellInstance.Commands.Clear();
powerShellInstance.Commands.AddCommand(new Command("Get-MyParameter"));
powerShellInstance.AddScript(psScript);
var result = powerShellInstance.Invoke();
What am I doing wrong here?
You are adding the script to the same pipeline you added the Get-MyParameter
command to. In effect, you are doing
get-myparameter | { … your script … }
Try using separate pipelines instead.
var result1 = powerShellInstance.AddCommand("Get-MyParameter").Invoke()
var result2 = powerShellInstance.AddScript(psScript).Invoke();
Also, you can simplify your module loading code to
powerShellInstance.AddCommand("Import-Module").
AddParameter("Name", @"..\CommandLets\bin\Debug\Commandlets.dll")).
Invoke();