1

I want to pass 3 parameter from c# to powershell function but the output it show all parameter in same line. How to fix it ?

This is powershell code

param (
    [string] $param1,
    [string] $param2,
    [string] $param3
)
# begin
function AddStuff($x, $y ,$z) 
{ 
   "x: $x;" 
   "y: $y;"
   "z: $z;"
}

AddStuff $param1, $param2, $param3
# end

This is c# code.

    RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
    Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
    runspace.Open();
    RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
    Pipeline pipeline = runspace.CreatePipeline();
    string scriptfile = @"C:\Users\test2.ps1";
    Command myCommand = new Command(scriptfile);
    CommandParameter testParam1 = new CommandParameter("param1", "paramvalue1");
    CommandParameter testParam2 = new CommandParameter("param2", "paramvalue2");
    CommandParameter testParam3 = new CommandParameter("param3", "paramvalue3");
    myCommand.Parameters.Add(testParam1);
    myCommand.Parameters.Add(testParam2);
    myCommand.Parameters.Add(testParam3);
    pipeline.Commands.Add(myCommand);
    Collection<PSObject> results = pipeline.Invoke();
    StringBuilder stringBuilder = new StringBuilder();
    foreach (PSObject obj in results)
    {
        stringBuilder.AppendLine(obj.ToString());
    }
    MessageBox.Show(stringBuilder.ToString());

when I run it show MessageBox like this.

   x: paramvalue1 paramvalue2 paramvalue3; 
   y: 
   z: 

That is wrong. Why it not show like this.

   x: paramvalue1 ; 
   y: paramvalue2 ;
   z: paramvalue3 ;
mklement0
  • 382,024
  • 64
  • 607
  • 775
user572575
  • 1,009
  • 3
  • 25
  • 45
  • **In PowerShell, functions are invoked _like shell commands_** - `foo arg1 arg2` - _not_ like C# methods - `foo(arg1, arg2)`; see [`Get-Help about_Parsing`](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_parsing). If you accidentally use `,` to separate arguments, you'll construct an _array_ that a function sees as a _single_ argument. To prevent accidental use of method syntax, use [`Set-StrictMode -Version 2`](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/set-strictmode) or higher, but note its side effects. – mklement0 Nov 22 '18 at 17:39

1 Answers1

2

In your PowerShell script, do not use commas to separate arguments when you call AddStuff:

AddStuff $param1 $param2 $param3

When you do

AddStuff $param1, $param2, $param3

you are actually creating a PowerShell array that contains $param1, $param2, and $param3; this array is then passed to the first parameter ($x) of AddStuff, which is why you got the unexpected output.

If you test your PowerShell script first in e.g., PowerShell ISE, you can spot these sort of problems much more easily, before worrying about how to call the script from C#.

Polyfun
  • 9,479
  • 4
  • 31
  • 39