2011-12-01 59 views
5

我試圖從C#運行PowerShell腳本。我沒有任何問題將字符串傳遞給腳本,但是當我嘗試將數組傳遞給powershell腳本時,會引發異常。 下面是C#代碼:C#傳遞數組到PowerShell腳本

string [] test = {"1","2","3","4"}; 

RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create(); 
Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration); 

runspace.ApartmentState = System.Threading.ApartmentState.STA; 
runspace.ThreadOptions = PSThreadOptions.UseCurrentThread; 

runspace.Open(); 
RunspaceInvoke invoker = new RunspaceInvoke(); 
invoker.Invoke("Set-ExecutionPolicy Unrestricted"); 

Pipeline pipeline = runspace.CreatePipeline(); 
Command myCmd = new Command(@"C:\test.ps1"); 
CommandParameter param = new CommandParameter("responseCollection", test); 
myCmd.Parameters.Add(param); 
pipeline.Commands.Add(myCmd); 

// Execute PowerShell script 
Collection<PSObject> results = pipeline.Invoke(); 

下面是PowerShell腳本:

param([string[]] $reponseCollection) 
$a = $responseCollection[0] 

每次代碼執行它拋出:

Cannot index into a null array. 

我知道這些代碼執行powershell腳本在將字符串傳遞到powershell腳本時是正確的,它已經過徹底測試。

回答

5

它完美對我很好。

我唯一注意到的是,在你的腳本參數中,你有$reponseCollection - 在響應中缺少s。除非你在這裏輸入錯誤,否則這就是原因。

它可能似乎與字符串一起工作,因爲當您分配/使用不存在的變量時,Powershell不關心(通常)。但是當你索引到一個空/不存在的變量時,它確實會拋出錯誤。

+0

我不能相信這是問題所在,我花了數小時才縮小了這是問題所在。 – firthh

-2

我認爲你需要傳遞數組的PowerShell在PowerShell中陣列格式的字符串,即

string test = "('1','2','3','4')"; 
+0

不能:(相同的錯誤 – firthh

相關問題