我試圖從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腳本時是正確的,它已經過徹底測試。
我不能相信這是問題所在,我花了數小時才縮小了這是問題所在。 – firthh