How to connect to O365 and Exchange Online using Powershell

The GUI of the Exchange Admin Center (https://outlook.office365.com/ecp) is a very useful tool for ad-hoc maintenance and many administrative activities. For bulk changes or advanced settings, you need to use Powershell. The Exchange Online PowerShell V2 module (abbreviated as the EXO V2 module) uses modern authentication and works with multi-factor authentication (MFA).

Installing the Powershell modules

Microsoft has a Powershell module that allows connecting to and handling the exchange online environment. You will find that many functionalities are handled via Exchange and thus this module.

Open a Powershell window as an administrator to install the required Powershell module. The following command will install this module:

Install-Module -Name Exchangeonlinemanagement

You only need to do this once per system.

I recommend adding a few more modules, as you will sooner or later need them for related management purposes. Do yourself a favor and install them as well.

Install-Module -Name AzureAD
Install-Module -Name MSOnline

The MSOnline module was the first Windows PowerShell Module for Azure Active Directory. Microsoft refers to this module as version 1.0. It provides functionality that is not yet available in the AzureAD module. This AzureAD module is referred to as version 2.0. Its full name is Azure Active Directory PowerShell for Graph. Microsoft recommends using the AzureAD module if possible.

Connecting to Exchange Online

After installing the module, you can connect to exchange online via:

Import-Module ExchangeOnlineManagement
Connect-ExchangeOnline -UserPrincipalName <UPN>

Replace <UPN> with the UPN (probably your e-mail address) of your online account. You will only be able to use Powershell cmdlets your account has permissions for.

If you get an error message about running scripts, follow these simple instructions to allow Powershell execution. A typical error message could be:

Import-Module : File <x> cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https://go.microsoft.com/fwlink/?LinkID=135170.

Disconnecting

Be sure to disconnect the remote Powershell session when you are finished. If you close the Powershell window without disconnecting the session, you could use up all the remote Powershell sessions available to you. If that happens you’ll need to wait for the sessions to expire. To help prevent denial-of-service (DoS) attacks, you’re limited by Microsoft to three open remote Powershell connections to your Exchange Online organization.

Disconnect-ExchangeOnline