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
parameter.Name.Trim()evaluates to$loopin the debugger? It needs to just beloop(i.e. remove the $ sign)