PowerShell: Connect to Exchange Online

I know there’s a number of scripts out there that can handle automating (or at least simplifying the process of connecting to Exchange Online – I’ve realized over the years, though, that there’s a number of tips and tricks that I’ve adopted to make my day to day life easier.

Here’s one of them…

I use this script block as the starting point for all my Exchange Online scripts – I wrote it because I was getting tired of having to redo my connection each time I re-ran the script, especially when you’re writing and testing a new script, and having to run it multiple times while you’re testing. Since then, I keep it in my PowerShell folder in OneDrive for Business (seriously, you do that, right? You’re not going to lose all your hard work if your system dies, are you?).

The first segment of my script checks to see if you already have an open connection to Exchange Online:

$exSession = Get-PSSession | Where {$_.ComputerName -match “ps.outlook.com” -and $_.State -match “Opened”}

If you’re already connected, it just reports it and moves on:


If not, the script will go ahead and prompt for credentials and then connect you to both Exchange Online and the MSOL Service:

if ($exSession.Count -ge 1){

Write-Host “Connected!” -ForegroundColor Green

}

else {

#Connect to Exchange Online

Write-Host “Connecting to Exchange Online” -ForegroundColor Green

$credential = Get-Credential

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

Connect-MsolService -Credential $credential

}

Like so:


Feel free to use this script block as part of your Office 365 / Exchange Online scripts – if you like, the whole script is available on GitHub. I have a few more of these scripts that I use in my day to day, I’ll be posting those next.

Good luck; have fun!

One thought on “PowerShell: Connect to Exchange Online

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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