Tips for Connecting to Office 365 using PowerShell in Hybrid Environments

Wednesday, April 16, 2014
The Office 365 portal and Exchange Admin Console are fairly powerful to allow you to manage your tenant and on-premises environments. But as you are no doubt aware, there are many administrative tasks that require you to use PowerShell.

The sequence you usually find on the web to connect to Office 365 via PowerShell is:
[PS] C:\>$LiveCred = Get-Credential -credential admin@contoso.onmicrosoft.com
[PS] C:\>$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $LiveCred -Authentication Basic -AllowRedirection
[PS] C:\>Import-PSSession $Session
If you are in a hybrid environment with Exchange and Office 365 you will discover that both environments have a lot of the same cmdlets, such as Get-Mailbox, Set-DistributionGroup, etc. This causes a conflict when the Office 365 PowerShell cmdlets are loaded within the Exchange Management Shell. You either need to connect to Office 365 PowerShell from a regular PowerShell console (separate window) or you need to use the -AllowClobber parameter, which overwrites the existing EMS cmdlets with the Office 365 versions. This is not ideal if you are working with both on-prem and cloud objects at the same time.

Proxy creation has been skipped for the following command ... Use the AllowClobber parameter if you want to shadow existing local commands
I wrote a PowerShell script called Connect-Office365.ps1 that overcomes these conflicts by using the -Prefix parameter with the Import-PSSession cmdlet. The Prefix parameter tells PowerShell to add the specified prefix to all cmdlets it loads from Office 365. For example, if you set the prefix to "cloud" the Get-Mailbox cmdlet for Office 365 becomes Get-cloudMailbox and the Get-Mailbox cmdlet still applies to on-prem. This way you can use both sets of cmdlets in the same EMS console. The script also connects to the MSOLService so you can use the MSOL cmdlets to manage Azure AD.

Connect-Office365.ps1 with "cloud" prefix
Here's the four line Connect-Office365.ps1 script:
$LiveCred = Get-Credential -credential "admin@contoso.onmicrosoft.com"
 
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $LiveCred -Authentication Basic -AllowRedirection

Import-PSSession $Session -WarningAction SilentlyContinue -Prefix cloud

Connect-MsolService -Credential $LiveCred
I usually copy the script to the C:\Windows folder on my Exchange servers and my management computer so it can be run from any directory whenever I need it.


No comments:

Post a Comment

Thank you for your comment! It is my hope that you find the information here useful. Let others know if this post helped you out, or if you have a comment or further information.