I have the following Powershell script.
param([String]$stepx="Not Working")
echo $stepx
I then try using the following C# to pass a parameter to this script.
using (Runspace space = RunspaceFactory.CreateRunspace())
{
space.Open();
space.SessionStateProxy.SetVariable("stepx", "This is a test");
Pipeline pipeline = space.CreatePipeline();
pipeline.Commands.AddScript("test.ps1");
var output = pipeline.Invoke();
}
After the above code snippet is run, the value "not working" is in the output variable. It should be "This is a test". Why is that parameter ignored?
Thanks
You're defining
$stepx
as a variable, which is not the same as passing a value to your script's$stepx
parameter.The variable exists independently of the parameter, and since you're not passing an argument to your script, its parameter is bound to its default value.
Therefore, you need to pass an argument (parameter value) to your script's parameter:
Somewhat confusingly, a script file is invoked via a
Command
instance, to which you pass arguments (parameter values) via its.Parameters
collection.By contrast,
.AddScript()
is used to add a string as the contents of an in-memory script (stored in a string), i.e., a snippet of PowerShell source code.You can use either technique to invoke a script file with parameters, though if you want to use strongly typed arguments (whose values cannot be unambiguously inferred from their string representations), use the
Command
-based approach (the.AddScript()
alternative is mentioned in comments):