After Disposing older Runspace and creating a new runspace, new runspace is having a connections of old runspace

Shubham Mishra 0 Reputation points
2023-09-08T12:48:49.95+00:00

When we create a runspace(runspace1) and Powershell(powershell1) session and then Connect to exchnage online using Connect-ExchangeOnline cmdlet. And then dispose the runspace and create a new runspcae(runspace2) and new Powershell session(powershell2) and run Get-ConnectionInformation cmdlet, it shows the connection details of exchange online which was created by runspace1.
And if we execute any cmdlet(Ex: Get-User,Set-Mailbox) with the runspace2 it is giving the error - The term 'Get-User' is not recognized as the name of a cmdlet, function, script file, or operable program.
Below is the detailed snippet.

Is this the expected scenario?

//create runspace1
                InitialSessionState iss = InitialSessionState.CreateDefault();
                iss.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.RemoteSigned;
                Runspace runspace1 = RunspaceFactory.CreateRunspace(iss);
                runspace1.Open();


                //create powershell session
                PowerShell powershell1 = PowerShell.Create();
                powershell1.Runspace = runspace1;


                //Creating secure password 
                StringBuilder cmd = new StringBuilder("$sec=ConvertTo-SecureString ");
                cmd.Append("'");
                cmd.Append("*******");
                cmd.Append("'");
                cmd.Append(" -AsPlainText -Force");
                powershell1.AddScript(cmd.ToString());
                Collection<PSObject> connectionResult1 = powershell1.Invoke();
                powershell1.Commands.Clear();
                cmd.Clear();

                //create credential.
                cmd.Append("$mycreds = New-Object System.Management.Automation.PSCredential(\"" + "****@*****.onmicrosoft.com" + "\",$sec)");
                powershell1.AddScript(cmd.ToString());
                Collection<PSObject> connectionResult2 = powershell1.Invoke();
                powershell1.Commands.Clear();
                cmd.Clear();

                //Connect to exchange online
                cmd.Append("Connect-ExchangeOnline -Credential $mycreds");
                powershell1.AddScript(cmd.ToString());
                Collection<PSObject> connectionResult3 = powershell1.Invoke();
                powershell1.Commands.Clear();
                powershell1.Streams.ClearStreams();
                cmd.Clear();



                // Get connection info from first powershell session
                powershell1.AddScript("Get-ConnectionInformation");
                Collection<PSObject> connectionResult4 = powershell1.Invoke();
                powershell1.Commands.Clear();
                powershell1.Streams.ClearStreams();
                powershell1.Dispose();
                powershell1 = null;

                //Discposing runspace1 
                runspace1.Close();
                 runspace1.Dispose();
                 runspace1 = null;
               

                //Creating 2nd runspace2 and powershell session 2
                InitialSessionState iss2 = InitialSessionState.CreateDefault();
                iss2.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.RemoteSigned;
                Runspace runspace2 = RunspaceFactory.CreateRunspace(iss2);
                runspace2.Open();
                PowerShell powershell2 = PowerShell.Create();
                powershell2.Runspace = runspace2;



                powershell2.AddScript("Get-ConnectionInformation");
                Collection<PSObject> connectionResult5 = powershell2.Invoke();
                powershell2.Commands.Clear();
                powershell2.Streams.ClearStreams();
                List<string> sessionIds = new List<string>();

                if (connectionResult5.Count > 0)
                {
                    foreach (PSObject sessionItem in connectionResult5)
                    {
                        string session = JsonConvert.SerializeObject(sessionItem.ImmediateBaseObject);
                        JObject sessionJsonObject = JObject.Parse(session);
                        string id = (string)sessionJsonObject["ConnectionId"];
                        sessionIds.Add(id);
                    }
                }

//executing cmdlet with runspace2
                String cmd1 = "Get-User";
                powershell2.AddScript(cmd1);
                Collection<PSObject> connectionResult6 = powershell2.Invoke();
                PSInvocationStateInfo info1 = powershell2.InvocationStateInfo;
                if (info1.State == PSInvocationState.Completed)
                {
                    if (powershell2.HadErrors && powershell2.Streams.Error.Count > 0)
                    {
                        foreach (var value in powershell2.Streams.Error)
                        {
                            if (value != null)
                            {
                                StringBuilder errors = new StringBuilder();
                                errors.AppendLine(value.InvocationInfo != null
                                    ? value.InvocationInfo.MyCommand.Name : cmd1.ToString());
                                if (value.Exception.Message != null)
                                {
                                    errors.AppendLine(" : " + value.Exception.Message);
                                }
                            }
                        }

                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,995 questions
Microsoft Exchange Online Management
Microsoft Exchange Online Management
Microsoft Exchange Online: A Microsoft email and calendaring hosted service.Management: The act or process of organizing, handling, directing or controlling something.
4,564 questions
Microsoft Exchange
Microsoft Exchange
Microsoft messaging and collaboration software.
558 questions
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,546 questions
PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,575 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Limitless Technology 44,376 Reputation points
    2023-09-11T14:49:41.64+00:00

    Hello there,

    It sounds like you want to dispose of the runspace automatically, on completion of the script.

    You can set up an event handler for the System.Management.Automation.PowerShell.InvocationStateChanged event, inside of which you can check for the Completed and Failed states and close the runspace then:

    Note: Register-ObjectEvent must be used to subscribe to the event; while it is possible in principle to subscribe by passing a script block directly to .add_InvocationStateChanged() on the PowerShell instance, execution will hang when you later call .EndInvoke().

    Hope this resolves your Query !!

    --If the reply is helpful, please Upvote and Accept it as an answer–


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.