As more and more companies move to Office 365, PowerShell Cmdlets and Scripts are becoming staples of Administrator toolsets. One issue that I have come across quite often is the Cmdlet overlap that occurs when using Remote PowerShell sessions to both Office 365, and Exchange 2010 on-premises simultaneously.
For example, let’s say that I have a hybrid environment with both Exchange 2010 mailboxes on-premises, and mailboxes in Office 365. If I wanted to use PowerShell to collect data from both environments using Get-Mailbox, there is a conflict because both environments use the Cmdlet. So what is the solution to this problem? Well one way would be to import, then remove sessions as as needed. This does work, but it is quite a cumbersome solution. Instead, adding a prefix while importing a session has proven to be a much easier solution to manage and execute.
The Import-PSSessionCmdlet contains a parameter named -Prefixwhich allows you to add a prefix to the noun portion of Cmdlets that are imported with a session. For an example scenario, I’ll first create an Exchange 2010 on-premises Remote PowerShell Session:
1 | $ExOnPremSession = New -PSSession -configuratonName Microsoft.Exchange -ConnectionURI http://ExchangeCasServer.domain.com/PowerShell/ -Authentication kerberos -WarningAction Silentlycontinue |
Then I’ll import the on-premises session:
1 | Import -PSSession $ExOnPremSession -Warningaction silentlycontinue |
Now that my on-premises session is connected, I will create a session to Office 365:
1 | $CloudSession = New -PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https:// ps .outlook.com/powershell -Credential $CloudCredential -Authentication Basic -AllowRedirection -WarningAction SilentlyContinue |
Then I will import the session using the chosen prefix “Cloud” :
1 | Import -PSSession $CloudSession -Prefix Cloud -DisableNameChecking |
Now if I want mailbox data for a user that is in Office 365, I can use my new prefix Cmdlet:
1 | Get -CloudMailbox Test.User1 | FL |
I can use any other Cmdlet offered for Office 365 Remote PowerShell too, just by attaching my prefix to the noun portion of the original Cmdlet:
1 | Get -CloudMailboxStatistics |
3 | Get -CloudActiveSyncDeviceStatistics |
And if I need to get mailbox data for a second user on-premises I can use the original Cmdlet:
1 | Get -Mailbox Test.User2 | FL |
So, even though I have multiple sessions imported with overlapping Cmdlets, I can still issue them to the proper platform with a simple prefix on each Cmdlet. This functionality has greatly simplified my Office 365 PowerShell scripts as they become more complex.