0

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?

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.