[英]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.