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 email@example.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
|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 “firstname.lastname@example.org”
$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.