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?