2012-08-07 103 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