C#将数组传递给powershell脚本

Hug*_*ugo 5 c# powershell

我正在尝试从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();
Run Code Online (Sandbox Code Playgroud)

这是powershell脚本:

param([string[]] $reponseCollection)
$a = $responseCollection[0]
Run Code Online (Sandbox Code Playgroud)

每次执行此代码时抛出:

Cannot index into a null array.
Run Code Online (Sandbox Code Playgroud)

我知道在将字符串传递给powershell脚本时执行powershell脚本的代码是正确的,它已经过全面测试.

man*_*lds 6

它对我来说非常好.

我注意到的唯一事情就是,在你的剧本中,你有$reponseCollection- 你的答案中缺少了.除非你在这里输入错误,否则就是这个原因.

它可能似乎与字符串一起使用,因为当您分配/使用不存在的变量时,Powershell不关心(通常).但是当你索引到一个null/non-existing变量时,它会抛出错误.