In my experience running powershell and Microsoft Exchange code in C# can be a little tricky. Here is what I had to do:
In your App.Config
add the useLegacyV2RuntimeActivationPolicy="true"
to the startup tag like so(you don't have to have .net 4.5) This allows the Microsoft.Exchange.Management.PowerShell.Admin to load properly(which you must have the Exchange Tools installed on the local computer to run).:
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
Then, assuming you have the System.Management.Automation
reference added to your project you can structure your Powershell query like so in C#:
string username = "username";
using (PowerShell PowerShellInstance = PowerShell.Create())
{
PowerShellInstance.AddScript("param ([string]$user); add-pssnapin 'Microsoft.Exchange.Management.PowerShell.Admin';" +
"get-mailbox -Identity $user -resultsize unlimited | select Name -expand EmailAddresses | Select SmtpAddress;");
PowerShellInstance.AddParameter("user", username);
Collection<PSObject> PSOutput = PowerShellInstance.Invoke();
if (PowerShellInstance.Streams.Error.Count > 0)
{
foreach (var error in PowerShellInstance.Streams.Error)
{
//for reading errors in debug mode
StringBuilder sb = new StringBuilder();
sb.AppendLine(error.Exception.Message);
sb.AppendLine(error.Exception.InnerException.Message);
sb.AppendLine(error.CategoryInfo.Category.ToString());
sb.AppendLine(error.CategoryInfo.Reason);
sb.AppendLine(error.ErrorDetails.Message);
sb.AppendLine(error.ErrorDetails.RecommendedAction);
Console.WriteLine(sb.ToString());
}
}
if (PSOutput.Count > 0)
{
foreach (var item in PSOutput)
{
Console.WriteLine(item);
}
}
}
I also had to change my project to build as x64 because the powershell addin for Exchange is 64-bit.