Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm attempting to run a powershell script from C#. 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. Here is the C# code:

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:

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.

share|improve this question

2 Answers

up vote 4 down vote accepted

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. 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. But when you index into a null / non-existing variable, it does throw the error.

share|improve this answer
I can't believe this was the problem. It took me hours to just narrow down that this is where the problem was. – firthh Dec 1 '11 at 5:38

I think that you need to pass the array to powershell as a string in powershell array format, i.e.,

string test = "('1','2','3','4')";
share|improve this answer
Nope :( Same error – firthh Dec 1 '11 at 5:28

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.