Share via


Connecting Powershell to your Office 365 Tenant to Manage Exchange and Azure AD Simultaneously

Background:

A common question that we have to go over with customers that are new to this service is how to connect to the tenant via Powershell. Here's how I go about it.

Pre-Requisites:

Install the following components

Sign-In Assistant:

https://www.microsoft.com/en-us/download/details.aspx?id=39267

Azure AD cmdlets:

https://go.microsoft.com/fwlink/p/?linkid=236297

Easy Method:

Copy and paste the following into powershell. Update YourTenantAdmin@tenant.onmicrosoft.com to your tenant admin account

Import-Module MSOnline
$O365Cred = Get-Credential YourTenantAdmin@tenant.onmicrosoft.com
$O365Session = New-PSSession –ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell -Credential $O365Cred -Authentication Basic -AllowRedirection
Import-PSSession $O365Session
Connect-MsolService –Credential $O365Cred

Powershell will prompt you for a password and will connect to the tenant

Advanced:
Pre-Requesite

Run powershell as an Administrator and run the following:

Set-ExecutionPolicy Unrestricted

1. Scripted Method w/ Password Prompt
Convert the easy method above into a powershell script / .PS1 file:

Import-Module MSOnline
$O365Cred = Get-Credential YourTenantAdmin@tenant.onmicrosoft.com
$O365Session = New-PSSession –ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell -Credential $O365Cred -Authentication Basic -AllowRedirection
Import-PSSession $O365Session
Connect-MsolService –Credential $O365Cred

Run it and Powershell will prompt only for your password and connect to the service

2. Script + Saved password (Warning: Your password will be saved in plain text in order for this to work).
Change PlainTextPassword to your password and change YourTenantAdmin@tenant.onmicrosoft.com to your tenant admin UPN, save it as a .PS1 File

Import-Module MSOnline
$SecPass = ConvertTo-SecureString "PlainTextPassword" -AsPlainText -Force
$O365Cred = New-Object System.Management.Automation.PSCredential ("YourTenantAdmin@tenant.onmicrosoft.com", $SecPass)
$O365Session = New-PSSession –ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell -Credential $O365Cred -Authentication Basic -AllowRedirection
Import-PSSession $O365Session
Connect-MsolService –Credential $O365Cred

Run it and Powershell will then connect to your O365 Tenant without a credential prompt. This method is very convenient, but I would only recommend it when running it as part of a process/scheduled task where you don't want a credential prompt or manually intervene. However, you can use it to connect to the tenant if you are not concerned with the security risks.

I hope it helps!

-Mitchel