Powershell忽略通过SessionStateProxy.SetVariable传递的参数

时间:2018-06-28 22:11:51

标签: c# powershell powershell-sdk

我有以下Powershell脚本。

param([String]$stepx="Not Working")
echo $stepx

然后我尝试使用以下C#将参数传递给此脚本。

        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(); 
        }

运行上述代码段后,输出变量中的值为“不工作”。应该是“这是一个测试”。为什么忽略该参数?

谢谢

1 个答案:

答案 0 :(得分:1)

您正在将$stepx定义为变量,这与将值传递到脚本的$stepx 参数不同。 br /> 该变量独立于参数而存在,并且由于您没有将 argument 传递给脚本,因此其参数绑定为其默认值。

因此,您需要将参数(参数值)传递给脚本的参数:

有些令人困惑的是,脚本{em> file 是通过Command实例调用的,您可以通过其.Parameters集合将参数(参数值)传递给该实例。

相反,.AddScript()用于添加字符串作为内存脚本(存储在字符串中)的 contents ,即 PowerShell源代码片段

您可以使用 两种技术来调用带有参数的脚本 file ,尽管如果您想使用强类型参数(其值不能(从其字符串表示形式中明确推断出),请使用基于Command的方法(注释中提到了.AddScript()的替代方法)

  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"
  }
相关问题