Advertisement
Guest User

Untitled

a guest
Dec 19th, 2018
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1. // GET api/updateContact
  2. [HttpGet]
  3. public JsonResult Get(string apiKey = "", string user = "defaultUser", string pass = "defaultPass")
  4. {
  5. // Establish the connection credentials to exchage powershell
  6. string connectionUri = "https://outlook.office365.com/powershell-liveid/";
  7. string loginPassword = pass;
  8. SecureString secpassword = new SecureString();
  9. foreach (char c in loginPassword)
  10. {
  11. secpassword.AppendChar(c);
  12. }
  13. PSCredential credential = new PSCredential(user, secpassword);
  14.  
  15. // Create a new PowerShell Instance to connect to exhange using our credentials
  16. PowerShell powershell = PowerShell.Create();
  17. PSCommand command = new PSCommand();
  18. command.AddCommand("New-PSSession");
  19. command.AddParameter("ConfigurationName", "Microsoft.Exchange");
  20. command.AddParameter("ConnectionUri", new Uri(connectionUri));
  21. command.AddParameter("Credential", credential);
  22. command.AddParameter("Authentication", "Basic");
  23. powershell.Commands = command;
  24.  
  25. // Run the PowerShell Instance to create a session to be used
  26. Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace();
  27. runspace.Open();
  28. powershell.Runspace = runspace;
  29. Collection<System.Management.Automation.PSObject> result = powershell.Invoke();
  30.  
  31. // Ensure the connection worked
  32. if (powershell.Streams.Error.Count > 0 || result.Count != 1)
  33. {
  34. Collection<ErrorRecord> errors = powershell.Streams.Error.ReadAll(); // Streams property is not available
  35.  
  36. string allErrors = "";
  37.  
  38. if (errors != null && errors.Count > 0)
  39. {
  40. foreach (ErrorRecord er in errors)
  41. {
  42. allErrors += er.Exception.ToString() + ", ";
  43.  
  44. }
  45. return new ApiFailedResponse("Failed to connect to exchange: " + allErrors).ToJsonResult();
  46. }
  47.  
  48. return new ApiFailedResponse("Failed to connect to exchange").ToJsonResult();
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement