代码之家  ›  专栏  ›  技术社区  ›  Dave

PowerShell忽略通过sessionstateproxy.setvariable传递的参数

  •  2
  • Dave  · 技术社区  · 6 年前

    我有以下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 回复  |  直到 5 年前
        1
  •  1
  •   mklement0    6 年前

    你在定义 $stepx 作为一个 变量 ,这与向脚本的 $stepx 参数 .
    变量独立于参数存在,并且由于您没有传递 论点 对于脚本,其参数绑定到其默认值。

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

    有点令人困惑的是,一个脚本 文件 通过调用 Command 实例,通过它传递参数(参数值) .Parameters 收藏。

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

    你可以用 任何一个 调用脚本的技术 文件 但是,如果要使用 强类型 参数(其值不能从其字符串表示形式中明确推断)使用 命令 -基于方法 .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"
      }
    
    推荐文章