Search code examples
c#powershellpowershell-remoting

call a remote powershell script with parameters from c# program


I have the next piece of code that works calling a remote powershell script ( the script is into the remote system ) but I would like to send parameters to script:

c# method:

public void RemoteConnection() 
{
   connectionInfo = new WSManConnectionInfo(false, remoteMachineName, 5985, "/wsman", shellUri, credentials);
   runspace = RunspaceFactory.CreateRunspace(connectionInfo);
   runspace.Open();
   Pipeline pipeline = runspace.CreatePipeline(path);
   var results = pipeline.Invoke();
   foreach (PSObject obj in results)
    Console.WriteLine(obj.ToString());
}

I tried to send parameters with CommandParameter but I obtained an error message:

Pipeline pipeline = runspace.CreatePipeline();
Command myCommand = new Command(path);
CommandParameter testParam0 = new CommandParameter("suma");
myCommand.Parameters.Add(testParam0);
CommandParameter testParam = new CommandParameter("x", "89");
myCommand.Parameters.Add(testParam);
CommandParameter testParam2 = new CommandParameter("y", "11");
myCommand.Parameters.Add(testParam2);
pipeline.Commands.Add(myCommand);

Error Message:

{"Cannot perform operation because operation \"NewNotImplementedException at offset 76 in file:line:column <filename unknown>:0:0\r\n\" is not implemented."}

I can call my powershell script(which is into my remote system ) in this way:

PS C:\grace\powershell> .\script1.ps1  -suma -x 9 -y 19
28
PS C:\grace\powershell> .\script1.ps1  -suma "9" "19"
28

How can I send through c# program parameters for my powershell script?


Solution

  • How it worked for me:

    public void RemoteConnection() 
    {
      connectionInfo = new WSManConnectionInfo(false, remoteMachineName, 5985, "/wsman", shellUri, credentials);
            runspace = RunspaceFactory.CreateRunspace(connectionInfo);
            runspace.Open();
            Pipeline pipeline = runspace.CreatePipeline(path);
    
            Command myCommand = new Command(path);
            CommandParameter testParam0 = new CommandParameter("-suma");
            myCommand.Parameters.Add(testParam0);
    
            CommandParameter testParam = new CommandParameter("x", "34");
            myCommand.Parameters.Add(testParam);
            CommandParameter testParam2 = new CommandParameter("y", "11");
            myCommand.Parameters.Add(testParam2);
    
            pipeline.Commands.Add(myCommand);
            var results = pipeline.Invoke();
            foreach (PSObject obj in results)
              Console.WriteLine(obj.ToString());
    }
    

    Note I'm sending the path to CreatePipeline and also to create a new Command (Maybe is necessary a further review)