C#将一个数组传递给PowerShell脚本

5

我正试图从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个回答

6

对我来说它完美地运作。

我注意到的唯一问题是,在您的脚本参数中,$reponseCollection缺少s。除非您在此处输入时出错,否则这将是原因。

使用字符串可能看起来有效,因为PowerShell不关心(通常)您是否分配/使用不存在的变量。但是当您索引到空/不存在的变量时,它确实会抛出错误。


我简直不敢相信这是问题所在。花了我数小时的时间才缩小范围,确定问题就出在这里。 - Hugo

-2

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接