Office 365 / Exchange Online PowerShell Scripts – part 1

At my first real confrontation with Office 365 and Exchange Online (about 7 months ago) I was really surprised by the fact that there are so little complete PowerShell scripts out there.

So with the help of my basic PowerShell knowledge (at that time) and my favorite search engine (no names here J) I build some scripts that we used for some big migrations to Office 365/Exchange Online.

This is the first post in a series where I will discuss every script I created or used and modified in a separate post.

In this fist post I’d like to share a way to create a function and adding it to your PowerShell profile so that you can quickly execute the function from any open PowerShell session when you need it.
I came across the following post from Thomas Ashworth: and added a section for connecting to Office 365 in one command. So the information in this post is based on the post of Thomas.

Start by creating a PowerShell profile if you do not already have one. The following one liner will create an empty PowerShell profile.

New-item $profile –itemtype file –force

Next open the profile file in Notepad. This step is easily performed from PowerShell using the following command.

notepad $profile

Copy and paste the following function into the profile, save the file, and restart PowerShell (or reload the profile).

Function Connect-ExchangeOnline




[Parameter(Mandatory = $False)]

[System.Management.Automation.PsCredential]$Credential = $Host.UI.PromptForCredential(“Enter MSOL Admin Credential”,

“Enter the username and password of an MSOnline Administrator account.”,



[Parameter(Mandatory = $False)]

[System.Uri]$Uri = “”


Import-Module MSOnline

        Connect-MsolService -Credential $Credential

        $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $Uri -Credential $Credential -Authentication “Basic” -AllowRedirection

Import-PSSession $session -AllowClobber

Return $session


From now on whenever you need to connect to Office 365 and/or run Exchange cmdlets, you can simply type “Connect-ExchangeOnline” directly at the PowerShell prompt.

In part 2 of this series I’ll share a script which creates Shared Mailboxes + security group and adds the appropriate members.

leave your comment