To perform a large number of tasks, especially custom automated tasks, it is necessary to connect to the Office 365 tenant with Powershell. If you are familiar with Powershell in Exchange then the commands are very similar. Clearly there are additional cmdlets that are relevant to Office 365 and in other articles we can explore those.
The main function however is to get the connection running in the first place. To do this you need to start up ‘Windows Powershell ISE’ from your desktop and Run As Administrator. The running as administrator is very important as it will not connect if you don’t.
As a pre-requisite to this you will need to install the Microsoft Office 365 Online Sign In Assistant. You can find the executable https://www.microsoft.com/en-us/download/details.aspx?id=41950
Secondly if you are wanting to perform any Azure AD Powershell or the MSOL (MS Online) User functions you will need those modules as well. This can be found by typing these commands into the Powershell console
If this is the very first time you have run this type of script on your machine, you will need to start by executing this command as a ‘one-off’.
After this point on your machine you will be able to run any kind of script via the Powershell ISE. Then you can use the following script to perform the connection.
$username = “firstname.lastname@example.org”
$password = ConvertTo-SecureString “xxxxxx” -AsPlainText -Force
$UserCredential = new-object -typename System.Management.Automation.PSCredential -ArgumentList $username, $password
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection Import-PSSession $Session
connect-MsolService -Credential $UserCredential
connect-AzureAD -Credential $UserCredential
Replace the items with Red X’s with the credentials for your tenant. The end result will look like this.
From here you can use normal Exchange style powershell to perform functions on Office 365.