Connecting to Exchange Online with a Certificate and C#

Viewed 312

Anyone using c# to connect to Exchange online? I am running into a problem that I can't seem to make progress on.

I have the following snippet of code trying to connect to exchange online:

public Runspace getSpace() {
    String schema = "http://schemas.microsoft.com/powershell/Microsoft.Exchange";
    Uri server = new Uri("https://outlook.office365.com/PowerShell");
    string certificateThumbprint = "thumbprint";

    WSManConnectionInfo connectionInfo = new WSManConnectionInfo(server, schema, certificateThumbprint);
    Runspace rsp = RunspaceFactory.CreateRunspace(connectionInfo );
    rsp.Open();
    return rsp;
}

Which results in:

System.Management.Automation.Remoting.PSRemotingTransportException:
Connecting to remote server outlook.office365.com failed with the following error message : For more information, see the about_Remote_Troubleshooting Help topic. at System.Management.Automation.Runspaces.AsyncResult.EndInvoke()

I know the cert is working because when I do the following I am able to connect:

Connect-ExchangeOnline -AppId "application guid" -Organization "tenent.onmicrosoft.com" -CertificateThumbprint "thumbprint"

Any ideas on what I could try next? Thanks!

2 Answers

For connecting to O365 with certificate thumbprint I use the following code, which works:

using (Runspace remoteRunspace = RunspaceFactory.CreateRunspace()){
remoteRunspace.Open();

using (PowerShell powershell = PowerShell.Create())
{
    powershell.Runspace = remoteRunspace;
    powershell.AddCommand("Import-Module");
    powershell.AddParameter("Name", "ExchangeOnlineManagement");
    powershell.Invoke();

    powershell.Commands.Clear();

    powershell.AddCommand("Connect-ExchangeOnline");
    powershell.AddParameter("AppId", "");
    powershell.AddParameter("CertificateThumbprint", "");
    powershell.AddParameter("Organization", "");
    powershell.Invoke();

    powershell.Commands.Clear();

    powershell.AddCommand("Get-EXOMailbox");
    powershell.AddParameter("Identity", "");
    powershell.Invoke();

    Collection<PSObject> results = powershell.Invoke();

    powershell.Commands.Clear();

    powershell.AddCommand("Disconnect-ExchangeOnline");
    powershell.Invoke();
}
remoteRunspace.Close();}
Related