c#将数组传递给powershell脚本

本文关键字:powershell 脚本 数组 | 更新日期: 2023-09-27 18:16:13

我正在尝试从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脚本时是正确的,它已经经过了彻底的测试。

c#将数组传递给powershell脚本

这对我来说很好。

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

它可能看起来与string一起工作,因为Powershell(通常)不关心您何时分配/使用不存在的变量。但是当你索引到一个null/不存在的变量时,它会抛出错误。

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

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