Created
July 6, 2011 21:47
-
-
Save fraga/1068426 to your computer and use it in GitHub Desktop.
How to connect to microsoft exchange online and retrieve info
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ExchangePowerShell | |
{ | |
public static PSCredential GetCredentials(string userName, string password) | |
{ | |
var securePassword = new SecureString(); | |
Array.ForEach(password.ToCharArray(), securePassword.AppendChar); | |
var cred = new PSCredential(userName, securePassword); | |
return cred; | |
} | |
public static ExchangeUser GetMSOnlineUser(string email, string credUserName, string credPassword) | |
{ | |
try | |
{ | |
PSSnapInException exception = new PSSnapInException(); | |
Runspace runspace = RunspaceFactory.CreateRunspace(); | |
runspace.RunspaceConfiguration.AddPSSnapIn("Microsoft.Exchange.Transporter", out exception); | |
var credentials = ExchangePowerShell.GetCredentials(credUserName, credPassword); | |
runspace.Open(); | |
Pipeline pipeline = runspace.CreatePipeline(); | |
Command MsOnlineUserCmd = new Command("Get-MSOnlineUser"); | |
CommandParameter credentialParam = new CommandParameter("Credential", credentials); | |
CommandParameter identityParam = new CommandParameter("Identity", email); | |
MsOnlineUserCmd.Parameters.Add(credentialParam); | |
MsOnlineUserCmd.Parameters.Add(identityParam); | |
pipeline.Commands.Add(MsOnlineUserCmd); | |
pipeline.Commands.Add("Out-String"); | |
Collection<PSObject> results = pipeline.Invoke(); | |
runspace.Close(); | |
StringBuilder stringBuilder = new StringBuilder(); | |
foreach (PSObject obj in results) | |
{ | |
stringBuilder.AppendLine(obj.ToString()); | |
} | |
return null; | |
} | |
catch (PSSnapInException snapException) | |
{ | |
return null; | |
} | |
catch (Exception exception) | |
{ | |
return null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment