繁体   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