2012-08-07 96 views
2

我准备调用powershell脚本并通过参数。我都希望最终通过一个以上的参数使用C#将变量赋值给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 
+1

不回答你的问题这么多的快速评论 - 您是否试图通过.NET与本地ADSI商店进行交互? http://stackoverflow.com/questions/1640022/adsi-library-control-for-net – 2012-08-07 16:13:13

+0

没有从来没有经历过的,但由于 – 2012-08-07 16:18:13

回答

3

这行代码:

CommandParameter testParam = new CommandParameter("test3"); 

创建一个名为test3有一个null值的参数。我怀疑你想创建一个名为参数如:

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

而且你的脚本需要进行配置,以接受参数,如:

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

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

尝试添加以下到脚本的顶部,并重新测试:

param([string]$username) 

另外,您可以将下面的行添加到脚本的顶部:

$username = $args[0] 

祝你好运。

+0

这有助于但作为组名 – 2012-08-07 16:03:19

+0

如果你被分配System.Management.Automation.Runspaces.CommandParameter打开PowerShell并使用该参数执行脚本,会发生什么情况? – 2012-08-07 16:05:54

+0

看看Keith的答案。看起来像你的C#的一个问题,以及你如何设置参数。 – 2012-08-07 16:11:07