C#将数组传递给powershell脚本

时间:2011-12-01 05:10:03

标签: 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();

这是powershell脚本:

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

每次执行此代码时,都会抛出:

Cannot index into a null array.

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

2 个答案:

答案 0 :(得分:6)

它对我来说非常好。

我唯一注意到的是,在你的脚本参数中,你有$reponseCollection - s在响应中缺失。除非你在这里输入错误,否则就是原因。

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

答案 1 :(得分:-2)

我认为您需要将数组作为powershell数组格式的字符串传递给powershell,即

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