I am not sure how to ask the exact question, but let me give a try, hopefully incrementally i can refine :)
I understand there is a limit on the number of powershell sessions that can be created (for ex: i tried a simple program to open powershell exchange remote sessions and it didnt allow me to create more 18 powershell sesssions. so i am assumings its a definite number)
On the other hand, how many runspaces i can create and open? in other words, can i simply create a new runspace whenever i tried to execute cmds - this way i dont need to worry about runsapce state as whenever i try to execute the cmd it always uses new runspace.
Scenario: I have created a remote session (to be precise psremote session to a mailbox exchange server - programmatically in C# .net). I have also created a runspace and using the runspace and powershell session i am executing the powershell cmds on the target server (i.e; on my excahnge server - please see code snippet #1 to see how i am executing a script block on a remote server)
Case: Assume that target server is restarted (i.e; the mailbox server that i created remote session restarted)
Issue: As soon as i restarted the server, the program throws that runspace is in invalid state (InvalidRunspaceStateException - http://msdn.microsoft.com/en-us/library/system.management.automation.runspaces.invalidrunspacestateexception(v=vs.85).aspx)
Question: What is the optimial way to fix it :)?
I know one easy way to fix it is by catching the invalidstate exception and creating the runsapce and remote session again - but is this the ideal way?
Is there any other optimal or nicer way to manage the session rather than catching the exception and creating runspace and the session again?
//(sample) CODE SNIPPET1 - EXECUTING PS CMDS ON REMOTE SERVER
Runspace rs = RunspaceFactory.CreateRunspace();
rs.Open();
using (Pipeline pipeline = rs.CreatePipeline())
{
if (null == session)
{
pipeline.Commands.Add(command);
}
else
{
Command cmd = new Command("invoke-command");
cmd.Parameters.Add("session", session);
cmd.Parameters.Add("scriptblock", ScriptBlock.Create(command.ToString()));
if (null != argumentList)
{
cmd.Parameters.Add("ArgumentList", argumentList);
}
pipeline.Commands.Add(cmd);
}
var results = pipeline.Invoke();
}
Btw, after some debugging this is what i found:
Please see the attached image (the PSsession.Runspace.RunspaceInfo.State is broken and Pssession.runspace.runspaceinfo.reason is not null (has exception)
Probably, whenver i see the runspace of a pssession is not opened, i should just create a new pssession.
Thanks in advance, Regards, Dreamer