2

I want to know if it is possible to create a new Powershell Runspace object from an old one.

I'm am going to do some powershell operations concurrently. I create powershell runspace every time and run certain commands. Let's say the first 5 commands are same for all operations. If I could run those commands only once for all operations and send a copy of the runspace to the multi threading method, it would be more efficient.

Means, I run some commands through a pipeline first.

Runspace runspace = RunspaceFactory.CreateRunspace()
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript("$var = 5"); //those 5 initial commands
pipeline.Invoke();

Now, I want to run certain commands concurrently.

Parallel.For(0, 5, new ParallelOptions { }, i => concurrentOperations(runspace, i));

The concurrentOperations method has been defined as this

private static void concurrentOperations(Runspace runspace, int i)
{
        Pipeline pipeline = runspace.CreatePipeline();
        pipeline.Commands.AddScript("$newVar = $var + " + i + "; $newVar"); //newer commands which differs for each operation
        runspace.Open();
        System.Collections.ObjectModel.Collection<PSObject> result = pipeline.Invoke();
        foreach (PSObject obj in result)
        {
            Console.WriteLine("obj" + i + " : " + obj);
        }
}

And now I encounter an exception that, "Pipelines cannot be run concurrently".

So, If I could make a copy of the runspace, the pipelines will be created for different runspaces only. But runspace doesnot have Clone() method in it.

Is there any way that I could achive this?

Shen Prabu
  • 130
  • 13
  • Don't `Clone()` runspaces, spin up a [`RunspacePool`](https://msdn.microsoft.com/en-us/library/system.management.automation.runspaces.runspacepool(v=vs.85).aspx) instead – Mathias R. Jessen May 20 '16 at 13:03
  • As far as I analyzed, in `RunspacePool` there are options to create new runspaces that I have to run all the commands in each runspaces. I want a set of initial commands should be run only one time for all operations. – Shen Prabu May 20 '16 at 13:23
  • You could modify the `InitialSessionState` of the `RunspacePool` to reflect the changes brought on by the first 5 commands, so that all the Runspaces in the Pool have the same modified state when you start invoking code – Mathias R. Jessen May 20 '16 at 13:34
  • I tired adding commands in `InitialSessionState.Commands`. But then I came to know that it is like user defined cmdlets can be added to the existing cmdlets. How to run commands already when creating runspaces from `RunspacePool` using `InitialSessionState`? – Shen Prabu May 20 '16 at 14:24

0 Answers0