Connect PowerShell to Exchange Online

Written on July 16, 2017

There are many examples on the internet that show how to remotely connect to Exchange Online PowerShell. Hopefully this post will provide better code, and better insight into the process.

The process consists of 2 steps:

  1. Creating a PSSession to Exchange Online
  2. Importing that PSSession
$session=New-PSSession -ConfigurationName 'Microsoft.Exchange' `
  -ConnectionUri '' `
  -AllowRedirection `
  -Authentication 'Basic' `
  -Credential (Get-Credential) `
  -ErrorAction 'Stop'

Import-PSSession $session

Putting this into a function is simple, but you may want some additional features.

Additional Considerations

I like to differentiate the Exchange Online cmdlets vs the OnPrem Exchange cmdlets. To do this, I simply add a prefix to the Exchange Online cmdlets.

Adding a prefix will allow you to, at a glance, determine where your code is intended to run. It also means that you can use both Exchange Online and OnPrem Exchange cmdlets in the same shell.

With that in mind, here's what I have come up with:

function Connect-ExchangeOnline {


    $credential=Get-Credential `
      -ErrorAction Stop

  $exchSession=New-PSSession -ConfigurationName 'Microsoft.Exchange' `
    -ConnectionUri '' `
    -AllowRedirection `
    -Authentication 'Basic' `
    -Credential $credential `
    -ErrorAction 'Stop'

    Write-Verbose "Adding prefix [$prefix]"
  Import-PSSession @importParam

The -Prefix parameter allows you to set one your self based on your needs. The 'AllowNull' attribute will let you specify null if you don't want a prefix. You can also AllowClobber if you want to overwrite your Exchange cmdlets.

If you work with Exchange Online regularly, I would recommend putting this function into your PowerShell profile so it is always ready to go.

Thanks for reading

PS> exit