繁体   English   中英

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

[英]Powershell ignores parameter passed via SessionStateProxy.SetVariable

我有以下 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(); 
        }

上面的代码片段运行后,值“not working”在输出变量中。 应该是“这是一个测试”。 为什么忽略该参数?

谢谢

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

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

有点令人困惑的是,脚本文件是通过Command实例调用的,您可以通过其.Parameters集合向其传递参数(参数值)。

相比之下, .AddScript()用于添加作为一个内存中脚本的内容(存储在字符串)字符串,即,PowerShell的源代码片段

您可以使用任何一种技术来调用带有参数的脚本文件,但如果您想使用强类型参数(其值不能从它们的字符串表示中明确推断),请使用基于Command的方法(提到了.AddScript()替代方法.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"
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM