我正试图从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脚本的代码是正确的,它经过了彻底的测试。