Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static void ConnectToPowerShell()
- {
- string password = "password";
- string userName = "Administrator";
- System.Uri uri = new Uri(@"http://ExchangeServer/powershell?serializationLevel=Full");
- System.Security.SecureString securePassword = String2SecureString(password);
- System.Management.Automation.PSCredential creds = new System.Management.Automation.PSCredential(userName, securePassword);
- Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace();
- PowerShell powershell = PowerShell.Create();
- PSCommand command = new PSCommand();
- command.AddCommand("New-PSSession");
- command.AddParameter("ConfigurationName", "Microsoft.Exchange");
- command.AddParameter("ConnectionUri", uri);
- command.AddParameter("Credential", creds);
- command.AddParameter("Authentication", "Default");
- PSSessionOption sessionOption = new PSSessionOption();
- sessionOption.SkipCACheck = true;
- sessionOption.SkipCNCheck = true;
- sessionOption.SkipRevocationCheck = true;
- command.AddParameter("SessionOption", sessionOption);
- powershell.Commands = command;
- try
- {
- // open the remote runspace
- runspace.Open();
- // associate the runspace with powershell
- powershell.Runspace = runspace;
- // invoke the powershell to obtain the results
- Collection<PSSession> result = powershell.Invoke<PSSession>();
- String str=null;
- foreach (ErrorRecord current in powershell.Streams.Error)
- {
- // Console.WriteLine("The following Error happen when opening the remote Runspace: " + current.Exception.ToString() +
- // " | InnerException: " + current.Exception.InnerException);
- str = "The following Error happen when opening the remote Runspace: " + current.Exception.ToString() +
- " | InnerException: " + current.Exception.InnerException;
- MessageBox.Show(str);
- }
- if (result.Count != 1)
- throw new Exception("Unexpected number of Remote Runspace connections returned.");
- // Set the runspace as a local variable on the runspace
- powershell = PowerShell.Create();
- ...........................................
- ...........................................
- }
- Collection<PSSession> result = powershell.Invoke<PSSession>();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement