PowerShell connectivity to Azure, Exchange Online and Exchange on-premises all-in-one

I use the following function in my PowerShell profile so that I can use the Microsoft Online cmdlets, the Exchange cmdlets against Exchange online and the Exchange cmdlets against on-premises all in one session…

 

Firstly – If you are unsure how to create your PowerShell profile, you can do the following (from a PowerShell session) :

Test-Path $profile

If the results are FALSE, then you need to create your profile :

New-item –type file –force $profile

To modify your existing profile, or edit it after you’ve created it :

ii $profile

Now on to the function (paste this into your $profile) :

 

if (!(get-module MSONLINE)) {import-module MSONLINE}

Function Connect-Office365

{

[CmdletBinding()]

param

(

[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.”,“”,“userCreds”),

[Parameter(Mandatory = $False)]

[System.Uri]$Uri = “https://outlook.office365.com/powershell-liveid/”

)

connect-msolservice -credential $credential

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

Import-PSSession $session -prefix EXO -AllowClobber

Return $session

}

It’s important to note that if you run this on a system that doesn’t have the Exchange Management Shell (i.e. Your Exchange Server) or the Exchange ps-snapin loaded, you will only have Azure and Exchange Online in your session.   Making this function part of your profile on an Exchange server will allow you to have all 3 (or loading the Exchange ps-snapin on your system).

 

It’s also important to note that I use the -prefix EXO switch for the ps-session command, so that all the Exchange Online cmdlets (e.g. get-mailbox) will need to be prefixed with EXO (e.g. get-EXOmailbox) while the on-premises Exchange cmdlets (e.g. get-mailbox) will stay the same.

 

Lastly, if you find that you need to use a proxy server, you can add the following line before the $session = New-PSSession line :

$proxysettings = New-PSSessionOption -ProxyAccessType IEConfig

And add the following to the end of the $session = New-PSSession line :

-SessionOption $proxysettings

 

To use this new function, just launch PowerShell and type Connect-Office365, you will be prompted for your tenant credentials and will be connected to Azure and Exchange Online.