Search code examples
c#powershellpowershell-sdk

Powershell ignores parameter passed via SessionStateProxy.SetVariable


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


Solution

  • 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):

      using (Runspace space = RunspaceFactory.CreateRunspace())
      {
        space.Open();
    
        Pipeline pipeline = space.CreatePipeline();
    
        // Create a Command instance that runs the script and
        // attach a parameter (value) to it.
        // Note that since "test.ps1" is referenced without a path, it must
        // be located in a dir. listed in $env:PATH
        var cmd = new Command("test.ps1");
        cmd.Parameters.Add("stepx", "This is a test");
    
        // Add the command to the pipeline.
        pipeline.Commands.Add(cmd);
    
        // Note: Alternatively, you could have constructed the script-file invocation
        // as a string containing a piece of PowerShell code as follows:
        //   pipeline.Commands.AddScript("test.ps1 -stepx 'This is a test'");
    
        var output = pipeline.Invoke(); // output[0] == "This is a test"
      }