使用C#将变量分配给powershell

时间:2012-08-07 15:56:38

标签: c# powershell variable-assignment pipeline

我想调用一个powershell脚本并传递一个参数。我最终都希望通过一个以上的参数

        RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
        Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
        runspace.Open();
        RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);

        Pipeline pipeline = runspace.CreatePipeline();

        String scriptfile = "..\\..\\Resources\\new group.ps1";

        Command myCommand = new Command(scriptfile, false);

        CommandParameter testParam = new CommandParameter("test3");

        myCommand.Parameters.Add(testParam);


        pipeline.Commands.Add(myCommand);
        Collection<PSObject> psObjects;
        psObjects = pipeline.Invoke();
        runspace.Close();

问题似乎是......没有任何反应。这是如何正确分配变量?给测试PowerShell脚本

# creates group
net localgroup $username /Add
# makes folder
#mkdir $path

2 个答案:

答案 0 :(得分:4)

这行代码:

CommandParameter testParam = new CommandParameter("test3");

创建名为test3的参数,其值为null。我怀疑你想要创建一个命名参数,例如:

CommandParameter testParam = new CommandParameter("username", "test3");

并且您需要将脚本配置为接受参数,例如:

--- Contents of 'new group.ps1 ---
param([string]$Username)
...

答案 1 :(得分:1)

需要设置PowerShell脚本以接受参数:

尝试将以下内容添加到该脚本的顶部并重新测试:

param([string]$username)

或者,您可以将以下行添加到脚本的顶部:

$username = $args[0]
祝你好运。