你在定义
$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"
}