Powershell ignores parameter passed via SessionStateProxy.SetVariable

你离开我真会死。 提交于 2019-12-30 11:11:33

问题


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


回答1:


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"
  }


来源:https://stackoverflow.com/questions/51091859/powershell-ignores-parameter-passed-via-sessionstateproxy-setvariable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!