2

我想调用一个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
4

2 回答 2

4

这行代码:

CommandParameter testParam = new CommandParameter("test3");

创建一个名为test3null 的参数。我怀疑你想创建一个命名参数,例如:

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

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

--- Contents of 'new group.ps1 ---
param([string]$Username)
...
于 2012-08-07T16:07:09.740 回答
1

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

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

param([string]$username)

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

$username = $args[0]

祝你好运。

于 2012-08-07T16:00:05.943 回答