Skip to content

Instantly share code, notes, and snippets.

@fraga
Created July 6, 2011 21:47
Show Gist options
  • Save fraga/1068426 to your computer and use it in GitHub Desktop.
Save fraga/1068426 to your computer and use it in GitHub Desktop.
How to connect to microsoft exchange online and retrieve info
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