MarkC on UC Microsoft Skype for Business, Lync, Exchange & Everything Else

Connecting to Office365 with PowerShell

Connect to Office365, Exchange Online, and Azure Active Directory using Powershell.

====
More of a place-holder this one but how do you connect to Office365 Exchange Online using PowerShell? Fortunately, it’s pretty easy - note below is wrapped for readability, there’s 3 distinct commands involved:

$cred=get-credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Authentication Basic -AllowRedirection -Credential $cred
Import-PSSession $session

Easy hey?

The ‘get-credential’ prompts you for your login information, and stores it in the $cred variable. The $session configures the session using those credentials, and then the import-psession imports that session you stored. You can now use the Exchange Online PowerShell tools.

What about if you want to connect to Office365 Azure Active Directory to manage user accounts? Well, you need stuff for that. You need to install the
Windows Azure AD Module - download and install it from that link. You can read about the general requirements to Manage Azure AD Using Windows PowerShell here.

Once they’re installed you can connect to the Office365 Azure with ‘connect-msolservice’ - it’ll prompt you for your credentials, and then you’re in.

Personally, what I tend to do is have a PowerShell script that connects to Azure Active Directory and also sets up a session to Exchange Online - I don’t want to be typing those commands in all the time.

Again it’s simple and easy to do - create a PowerShell script called ‘ConnectOffice365.ps1’ and make it look like this (the bit between the ==== markers of course, also watch out for the $Session line, it’ll probably wrap - needs to be on the same line).

NOTE: The ‘import-module “MSOnline”’ has a dependency on the Windows Azure AD Module mentioned earlier.

====
Import-Module “MSOnline”
$cred=get-credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Authentication Basic -AllowRedirection -Credential $cred
Import-PSSession $session
Connect-msolservice -credential $cred
====

Next, we'll create a shortcut to PowerShell that runs the script, and importantly runs with the ‘no exit’ option. So your shortcut would be something like:

powershell.exe -noexit ConnectOffice365.ps1

If you’ve put the script in a folder other than the default you’ll need to use the full path for the script name. Now when you run that script it’ll ask you for your Office365 credentials, and then setup your Azure and ExchangeOnline sessions. Very handy.

blog comments powered by Disqus