Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Powershell忽略通过SessionStateProxy.SetVariable传递的参数_C#_Powershell_Powershell Sdk - Fatal编程技术网

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

C# Powershell忽略通过SessionStateProxy.SetVariable传递的参数,c#,powershell,powershell-sdk,C#,Powershell,Powershell Sdk,我有以下Powershell脚本 param([String]$stepx="Not Working") echo $stepx 然后,我尝试使用以下C#将参数传递给该脚本 using (Runspace space = RunspaceFactory.CreateRunspace()) { space.Open(); space.SessionStateProxy.SetVariable("stepx", "Th

我有以下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(); 
        }
运行上述代码段后,输出变量中会出现值“notworking”。应该是“这是一次测试”。为什么忽略该参数


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

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

有点令人困惑的是,脚本文件是通过
命令
实例
调用的,您可以通过它的
.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"
  }