Helper Function for Connecting to Exchange Online PowerShell

I’ve been doing a bit of work against Office 365 and Exchange Online recently as part of a migration from Exchange 2010 to Office 365.

Here’s a couple of basic helper functions that I’ve included in my PowerShell profile to make connecting to Exchange Online a little easier:

function Connect-ExchangeOnline() {
    $upn = ([ADSISEARCHER]"samaccountname=$($env:USERNAME)").Findone().Properties.userprincipalname
    $creds = Get-Credential -UserName $upn -Message "Enter password for $upn"
    $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $creds -Authentication Basic -AllowRedirection

    Import-PSSession $session

    Write-Output "`n`n`nDon't forget to 'Remove-PSSession `$session' or 'Disconnect-ExchangeOnline' when you're done"
}

function Disconnect-ExchangeOnline() {
    if ($session) { 
        Remove-PSSession $session
    } else {
        Get-PSSession | Remove-PSSession
    }

    "$((Get-PSSession | Measure-Object).Count) PowerShell session(s)"
}

What the Connect-ExchangeOnline function does is build on Microsoft’s own instructions to automatically detect the current user’s UPN, and use that in the prompt for credentials:

PowerShell Prompt showing an authentication popup that has the username field pre-filled with the current user's UPN

After that, it’s business as usual:

image

I also have a similar set of helper functions that I use for connecting to Exchange on-prem.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s