Skip to content

Instantly share code, notes, and snippets.

@gscales
Last active July 24, 2020 00:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gscales/d9d49fcab122f4327035b98cabfd1b41 to your computer and use it in GitHub Desktop.
Save gscales/d9d49fcab122f4327035b98cabfd1b41 to your computer and use it in GitHub Desktop.
MSAL Exchange Online Powershell Interactive Logon
string MailboxName = "gscales@datarumble.com";
string scope = "https://outlook.office365.com/.default";
string ClientId = "a0c73c16-a7e3-4564-9a95-2bdf47383716";
PublicClientApplicationBuilder pcaConfig = PublicClientApplicationBuilder.Create(ClientId);
pcaConfig.WithAuthority(AadAuthorityAudience.AzureAdMultipleOrgs, false);
var TokenResult = pcaConfig.Build().AcquireTokenInteractive(new[] { scope })
.WithPrompt(Prompt.SelectAccount)
.WithLoginHint(MailboxName).ExecuteAsync().Result;
System.Security.SecureString secureString = new System.Security.SecureString();
foreach (char c in ("bearer " + TokenResult.AccessToken))
secureString.AppendChar(c);
String WSManURIConnectionString = "https://outlook.office365.com/powershell-liveid?DelegatedOrg=" + MailboxName.Split('@')[1] + "&BasicAuthToOAuthConversion=true";
PSCredential credential = new PSCredential(MailboxName, secureString);
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri(WSManURIConnectionString), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", credential);
connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;
connectionInfo.SkipCACheck = true;
connectionInfo.SkipCNCheck = true;
connectionInfo.MaximumConnectionRedirectionCount = 4;
Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(connectionInfo);
runspace.Open();
// Make a Get-Mailbox requst using the Server Argument
Command gmGetMailbox = new Command("get-mailbox");
gmGetMailbox.Parameters.Add("ResultSize", "Unlimited");
Pipeline plPileLine = runspace.CreatePipeline();
plPileLine.Commands.Add(gmGetMailbox);
Collection<PSObject> RsResultsresults = plPileLine.Invoke();
Dictionary<string, PSObject> gmResults = new Dictionary<string, PSObject>();
foreach (PSObject obj in RsResultsresults)
{
Console.WriteLine(obj.Members["WindowsEmailAddress"].Value.ToString());
}
Command gmGetUser = new Command("get-user");
plPileLine.Stop();
plPileLine.Dispose();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment