anonmous
anonmous

Reputation: 139

How to Inject an Array Variable into a PowerShell Runspace via New-Variable

Assume I have created and opened runspace via

            var rs = RunspaceFactory.CreateRunspace();
            rs.Open();

Let's further assume that I want to add a variable into that runspace that is typed as an array by using the New-Variable cmdlet like so:

            // create a pipeline to add the variable into the runspace
            var pipeline = PowerShell.Create();
            // create a command object, add commands and parameters to it...
            var cmd = new PSCommand();
            cmd.AddCommand("New-Variable");
            cmd.AddParameter("Name", "foo");
            cmd.AddParameter("Value", "@()");
            // associate the command with the pipeline and runspace, and then invoke
            pipeline.Commands = cmd;
            pipeline.Runspace = rs;
            pipeline.Invoke();

The code works and I get no errors, but the variable 'foo' is not created as an array type. I've tried many different variations on "@()", but none of them have panned out thus far. Ultimately, I think the question boils down to how to properly format the Value argument to New-Variable so that 'foo' will be interpreted as an empty PowerShell array type.

Thanks,

Matt

Upvotes: 1

Views: 2732

Answers (3)

ghofrane rhimi
ghofrane rhimi

Reputation: 1

the response that saved me is:

If you are doing it all from text, you can look at the AddScript methods. For example, var cmd = new PSCommand().AddScript("$myVar = @()"); will generate a new variable named $myVar.

Example in C# code :

foreach (Collaborator collab in collabs)
                {
                    counter ++;
                    arrayUsers.Append("@(\"" + collab.mail + "\", \"" + collab.url + "\")");
                    if (counter < numbercollabs)
                        arrayUsers.Append(",");
                }
                string arrayUsersPowerShell =  arrayUsers.ToString();
and then :

using (PowerShell powerShellInstance = PowerShell.Create())
                {
 powerShellInstance.AddScript("$d = get-date; " +
                        "$arrayUsers = @(" + arrayUsersPowerShell + "); " +
                        "$d | Out-String; $arrayUsers[0][1]");
...
Collection<PSObject> PSOutput = powerShellInstance.Invoke();
...
}

So we can construct the array correctly

Upvotes: 0

Keith Hill
Keith Hill

Reputation: 201672

FYI, you can do this directly in C# like so:

pipeline.Runspace.SessionStateProxy.PSVariable.Set("foo", new object[0]);

Upvotes: 4

latkin
latkin

Reputation: 16792

PSCommand.AddParameter takes a string for the parameter name, and an object for the parameter value. See the docs here.

You should put a "real" empty array, not a string representing the powershell script equivalent.

cmd.AddParameter("Value", new object[0]);

Upvotes: 0

Related Questions