簡體   English   中英

C#將數組傳遞給powershell腳本

[英]C# passing an array to a powershell script

我正在嘗試從C#運行一個powershell腳本。 我沒有問題將字符串傳遞給腳本但是當我嘗試將數組傳遞給powershell腳本時,會拋出異常。 這是C#代碼:

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腳本的代碼是正確的,它已經過全面測試。

它對我來說非常好。

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

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

我認為您需要將數組作為powershell數組格式的字符串傳遞給powershell,即

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM