Initiating powershell connection with WSManConnectionInfo

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
I have the following code that creates a connection to exchange in powershell
<pre class="prettyprint public void connect(string username, string password)
{

SecureString pass = new SecureString();

foreach (Char character in password)
{
pass.AppendChar(character);
}



PSCredential creds = new PSCredential(username + "@crescentmortgage.net", pass);

WSManConnectionInfo connectionInfo = new WSManConnectionInfo(
new Uri("https://ch1prd0802psh.outlook.com/PowerShell-LiveID?PSVersion=2.0"),
"http://schemas.microsoft.com/powershell/Microsoft.Exchange", creds);
connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;



Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo);
runspace.Open();



loginpanel.Visible = false;
controlpanel.Visible = true;


}[/code]
I then have this method that gets the mailboxes
<pre class="prettyprint private void pictureBox1_Click_1(object sender, EventArgs e)
{

Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();



Pipeline pipeline = runspace.CreatePipeline();




pipeline.Commands.Add("Get-Mailbox");



Collection<PSObject> commandResults = pipeline.Invoke();

StringBuilder sb = new StringBuilder();

ArrayList boxesarray = new ArrayList();

foreach (PSObject ps in commandResults)
{




sb.AppendLine(ps.Properties["Alias"].Value.ToString());



}



label4.Text = sb.ToString();

}[/code]
My problem or question is do I need to create a new runspace everytime in every method I want to use a cmdlet for that connection. Or is there a way to initiate the initial connection in a runspace and then use that runspace in my other methods?

If I try the code above I get an error saying the cmdlet is not a valid one because it doesnt have the connection info anymore I am guessing.

Any ideas on reusing the same runspace?

Thanks,


View the full article
 
Back
Top