简体   繁体   English

C#将数组传递给powershell脚本

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

I'm attempting to run a powershell script from C#. 我正在尝试从C#运行一个powershell脚本。 I have no problem passing strings to the script however when I try to pass an array to the powershell script an exception gets thrown. 我没有问题将字符串传递给脚本但是当我尝试将数组传递给powershell脚本时,会抛出异常。 Here is the C# code: 这是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();

Here is the powershell script: 这是powershell脚本:

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

Every time this code executes it throws: 每次执行此代码时抛出:

Cannot index into a null array.

I know that the code to execute the powershell script is correct when passing strings to the powershell script, it has been thoroughly tested. 我知道在将字符串传递给powershell脚本时执行powershell脚本的代码是正确的,它已经过全面测试。

It works perfectly fine for me. 它对我来说非常好。

Only thing I notice is that, in your script params you have $reponseCollection - the s is missing in response. 我唯一注意到的是,在你的脚本参数中你有$reponseCollection - 响应中缺少s。 Unless you made a mistake in entering it here, that would be the reason. 除非你在这里输入错误,否则就是这个原因。

It might have seemed to work with string because Powershell doesn't care ( normally) when you assign / use a non-existing variable. 它可能似乎与字符串一起使用,因为当您分配/使用不存在的变量时,Powershell不关心(通常)。 But when you index into a null / non-existing variable, it does throw the error. 但是当你索引到一个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