Powershell function for Exchange online

Working as a consultant for multiple customers forces us to connect multiple times a day to different Exchange Online management shell’s. Everyone has his own way to save the connection command for the Exchange Online PowerShell. I had the command always saved in a ready to use Notepad document.

However, since I am always using the same devices for work, we created a small PowerShell function which makes it easier and faster to connect to customers Exchange Online environments.

 

The Function

function Connect-ExchangeOnline
{
	<#
.NOTES
===========================================================================
Created on: 08.02.2019 14:43
Created by: Dominic Manning | Drago Petrovic
Website: https://www.msb365.blog
Name: Connect-ExchangeOnline
===========================================================================
.Synopsis
   Connect-ExchangeOnline is a PowerShell function to ease the connection to Exchange Online
.DESCRIPTION
   Function to connect to Exchange Online services. 
	If the function was executed before in the same PoSH session you can re-use the credentials provided before.
	You can also specify a specific O365 tenant domain to connect to if you provide the
	parameter "Tenant"
.EXAMPLE
   Connect-ExchangeOnline -Tenant contoso.onmicrosoft.com
	Will connect to the tenant domain contoso.onmicrosoft.com
.EXAMPLE
   Connect-ExchangeOnline
	Will connect to the default tenant domain of your specified credentials.
.EXAMPLE
	Disconnect-ExchangeOnline
	Disconnects the session.

#>
	
	param
	(
		[Parameter(Mandatory = $false)]
		[String]$Tenant
	)
	# First check if we have credentials from a former execution 
	# and ask if we want to use those credentials again to connect
	if ($O365creds -ne $null)
	{
		$yn = Read-Host "Found O365 credentials for $($O365creds.username). Use those?[Y/N] Default is [Y]"
		switch ($yn)
		{
			"y" {
				"Using credentials for $($O365creds.username)"
				$oldcreds = $true
			}
			"N" {
				$oldcreds = $false
			}
			default
			{
				"Using credentials for $($O365creds.username)"
				$oldcreds = $true
			}
		}
	}
	# Ask for credentials if no old credentials were found, or by user input specified not to use them
	if ($O365creds -eq $null -or $oldcreds -eq $false)
	{
		$global:O365creds = (Get-Credential -Message "Enter your O365 / Exchange Online credentials")
		if ($O365creds -eq "" -or $O365creds -eq $null)
		{
			#Exit if no credentials are provided
			"No credentials provided. Exiting."
			return
		}
	}
	
	try
	{
		"Creating session..."
		#If a tenant domain name was specified use that name in the connection URI
		if ($tenant -ne "")
		{
			#Create the session with domain name in the URI
			$global:o365session = New-PSSession -ConfigurationName Microsoft.Exchange -uri https://ps.outlook.com/powershell-liveid?DelegatedOrg=$tenant -Credential $O365Creds -Authentication Basic -AllowRedirection -Name "Exchange Online" -ErrorAction Stop
		}
		else
		{
			#Create the session
			$global:o365session = New-PSSession -ConfigurationName Microsoft.Exchange -uri https://ps.outlook.com/powershell-liveid? -Credential $O365Creds -Authentication Basic -AllowRedirection -Name "Exchange Online" -ErrorAction Stop
		}
		
	}
	catch
	{
		Write-Error "Could not connect to O365"
		$_.Exception.Message
		
	}
	"Importing session"
	#Import the session through import module "-Global" so the cmdlets are globally available if run as module.
	Import-Module(Import-PSSession $o365session -ErrorAction Stop) -Global -ErrorAction Stop
	cls
	Write-Host "Connected to Exchange Online. Sponsored by MSB365.blog" -ForegroundColor Green
}

function Disconnect-ExchangeOnline
{
	if (Get-PSSession -Name "Exchange Online")
	{
		Remove-PSSession -Name "Exchange Online"
		"Session disconnected"
	}
}

How to use the Function

Copy the code into your PowerShell, or PowerShell ISE session and run it. Then type Connect-ExchangeOnline and have fun with it.

If we want to make the function permanently available so it’s is there every time we start PowerShell, we have to create a folder in C:\Program Files\WindowsPowerShell\Modules. This folder we name Connect-ExchangeOnline. After that we save the code (our function) as a .psm1 file in that folder. 

To see an example, have a look on the picture below:

 

 

Connect to Exchange online

I want to show you first what we are going to achieve.

After starting the default Windows PowerShell cmdlet, we simply hit the command Connect-ExchangeOnline and we get prompted to the logon windows for our credentials. Depending on which credentials we are using here, we are going to be connected to our environment.

 

If we are managing multiple Exchange online instances (As CSP for example) we can run the following command:

Connect-ExchangeOnline -Tenant contoso.onmicrosoft.com

 

 

Get the function

This function can easily be copied out from this article or downloaded from the Microsoft Technet by following the link below:

https://gallery.technet.microsoft.com/Powershell-function-for-b8eddf32

 

 

 

Photo by Malcolm Lightbody on Unsplash


Leave a Reply

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