Connecting to Office 365 Exchange Using Powershell

Some administrative tasks require you to connect to Office 365 using Powershell because they are not available on the GUI. Once you are familiar with Powershell and the cmdlets required for certain Office 365 tasks you may actually find it a more efficient way to administer Office 365.

In this article, we outline the steps required to connect to Office 365 from Powershell with explanations of each part. At the end of the article, the commands are combined into a script that you can run to get connected.

1) Script Execution Policy

Before your computer will allow you to run the required cmdlets to connect to Powershell, it is necessary to change the script execution policy. This is a security policy that determines if you can run scripts and load configuration files and whether they must be digitally signed before they will run. For the purposes of this exercise, we need to allow remote signed scripts.

To run the command to allow remote signed scripts you must open Powershell as an administrator. You can then run the command shown below.

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned

Once you run the above code you will be asked to confirm that you want to make the change. Type “Y” and hit enter to confirm the change. If, for security reasons, you want to revert this back after completing your Office 365 administration tasks you can run the same command replacing RemoteSigned with Default.

2) Credentials

In order to connect to Office 365 through Powershell, you will need the credentials for a user that has administrative privileges. You will need to pass these through Powershell which can be done using the command below. This will store the credentials you enter as a variable in Powershell.

$UserCredential = Get-Credential

3) Session Configuration

The next step is to create a session configuration that establishes the connection to Office 365 and passes the credentials in order to log in. This session configuration will, again, be stored as a variable in Powershell until it is called upon later.

$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid -Credential $UserCredential -Authentication Basic -AllowRedirection

4) Import the Session

The final step to connect to Office 365 with Powershell is to run a command to import a session and call on the previous variable which will provide the session configuration.

Import-PSSession $Session

Full Script

Here is the final script that you can use to connect to your Office 365 tenant in order to run Exchange cmdlets through Powershell.

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
$UserCredential = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid -Credential $UserCredential -Authentication Basic -AllowRedirection
Import-PSSession $Session

Leave a Reply