Advertisement
Guest User

Untitled

a guest
Jan 26th, 2017
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.47 KB | None | 0 0
  1. public static void ConnectToPowerShell()
  2. {
  3. string password = "password";
  4. string userName = "Administrator";
  5.  
  6. System.Uri uri = new Uri(@"http://ExchangeServer/powershell?serializationLevel=Full");
  7. System.Security.SecureString securePassword = String2SecureString(password);
  8.  
  9. System.Management.Automation.PSCredential creds = new System.Management.Automation.PSCredential(userName, securePassword);
  10.  
  11. Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace();
  12.  
  13. PowerShell powershell = PowerShell.Create();
  14. PSCommand command = new PSCommand();
  15. command.AddCommand("New-PSSession");
  16. command.AddParameter("ConfigurationName", "Microsoft.Exchange");
  17. command.AddParameter("ConnectionUri", uri);
  18. command.AddParameter("Credential", creds);
  19. command.AddParameter("Authentication", "Default");
  20. PSSessionOption sessionOption = new PSSessionOption();
  21. sessionOption.SkipCACheck = true;
  22. sessionOption.SkipCNCheck = true;
  23. sessionOption.SkipRevocationCheck = true;
  24. command.AddParameter("SessionOption", sessionOption);
  25.  
  26. powershell.Commands = command;
  27.  
  28. try
  29. {
  30. // open the remote runspace
  31. runspace.Open();
  32.  
  33. // associate the runspace with powershell
  34. powershell.Runspace = runspace;
  35.  
  36. // invoke the powershell to obtain the results
  37. Collection<PSSession> result = powershell.Invoke<PSSession>();
  38. String str=null;
  39. foreach (ErrorRecord current in powershell.Streams.Error)
  40. {
  41. // Console.WriteLine("The following Error happen when opening the remote Runspace: " + current.Exception.ToString() +
  42. // " | InnerException: " + current.Exception.InnerException);
  43. str = "The following Error happen when opening the remote Runspace: " + current.Exception.ToString() +
  44. " | InnerException: " + current.Exception.InnerException;
  45. MessageBox.Show(str);
  46. }
  47. if (result.Count != 1)
  48. throw new Exception("Unexpected number of Remote Runspace connections returned.");
  49.  
  50. // Set the runspace as a local variable on the runspace
  51. powershell = PowerShell.Create();
  52. ...........................................
  53. ...........................................
  54. }
  55.  
  56. Collection<PSSession> result = powershell.Invoke<PSSession>();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement