Connect to Office 365/Azure AD through PowerShell

PowerShell is something you will need to get familiar with in order to be an efficient Office 365 administrator. In fact some tasks can only be done through PowerShell and a lot of bulk tasks are just a pain in the ass to do manually. This post will guide you through the installation of the prerequisites and how to connect to the Office 365 tenant.

Requirements

The computer requirements are:

  1. It needs to be a 64-bit machine.
  2. OS needs to be Windows 7 SP 1 or later (Windows 8, Windows 8.1, Windows 10) or Windows Server 2008 R2 SP1 or later (Windows Server 2012, Windows Server 2012 R2, Windows Server 2016)

The prerequisites you will need to install are:

  1. 64-bit version of the Microsoft Online Services Sign-in Assistant
  2. 64-bit version of the Windows Azure Active Directory Module for Windows PowerShell

PowerShell

Now open PowerShell ISE. Type the following in the editor window and run the script.

$userCredential = Get-Credential
Connect-MsolService -Credential $UserCredential

You will be prompted for your credentials. Type in the username and password for a global administrator in the tenant you want to connect to. That’s it. To verify that you are connected run the command Get-MsolUser and see that the users in the tenant are returned in the PowerShell window.

If you for some reason should not be connected it is either because one of the installations above failed or that the PowerShell module is not loaded in your PowerShell session. To manually load the PowerShell module, put the following line at the top of your script.

Import-Module MSOnline

Please note that this will only connect you to the Office 365 admin center and not e.g. Exchange Online. Establishing a connection to the different services in Office 365 is covered in this post.

If you encountered an error saying “File cannot be loaded because running scripts is disabled on this system” you need to set the execution policy correct. See this post for instructions on how to do this.

Useful resources

Office 365 PowerShell (MSOnline) cmdlets documentation

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.