puneet
puneet

Reputation: 622

Execute Powershell Script text in c#, passing values to arguments in Param Section

I have a simple powershell script

param
(

   [Parameter(Mandatory=$true)]
   [int]$loop = 2
)

for ($i=0; $i -le $loop; $i++)
{
  $v += get-process
}

$v

I want to execute it through C#. I am able to execute simple scripts but now when I want to pass value to the $loop parameter it says

{"Cannot process command because of one or more missing mandatory parameters: loop."}

I am using the below code:

using (PowerShell powerShellInstance = PowerShell.Create(RunspaceMode.NewRunspace))
{
    powerShellInstance.Runspace = runspace;
    powerShellInstance.AddScript(script);

    if (parameters != null && parameters.Any())
    {
        foreach (var parameter in parameters)
        {
            if (parameter.Type == ParameterType.Int32)
            {
                int value = Convert.ToInt32(parameter.Value.Trim());
                powerShellInstance.AddParameter(parameter.Name.Trim(), value);
                }
            else
            {
                powerShellInstance.AddParameter(parameter.Name.Trim(), parameter.Value.Trim());
            }
        }
    }

Here, I see in the debug mode of visual studio that the parameter name is $loop and its value is being clearly set through the Addparameter Api

But I get the above exception when I call

Collection<PSObject> output = powerShellInstance.Invoke();

NOt sure, where am I going wrong. Please help

Upvotes: 1

Views: 1828

Answers (1)

Andy Schneider
Andy Schneider

Reputation: 8684

It would help to see the rest of your code where you define parameters and script. One thing to note is that the name of parameter is actually loop, not $loop.

Here is some very simplified code that shows this working.

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Management.Automation;
using System.Text;
using System.Threading.Tasks;

namespace PSTest
{
    class Program
    {
        static void Main(string[] args)
        {
            using (PowerShell powerShellInstance = PowerShell.Create(RunspaceMode.NewRunspace))
            {

                var script = "param($param1) $output = 'testing params in C#:' + $param1; $output";
                powerShellInstance.AddScript(script);
                powerShellInstance.AddParameter("param1", "ParamsinC#");
                Collection<PSObject> PSOutput = powerShellInstance.Invoke();

                foreach (PSObject outputItem in PSOutput)
                {

                    if (outputItem != null)
                    {
                        Console.WriteLine(outputItem);
                    }
                }
                Console.ReadKey();

            }
        }
    }
}

Upvotes: 3

Related Questions