Exchange Online and Exchange On-Premises Security Groups

I had a requirement come up where I needed a list of Exchange Online users as well as Exchange On-Premises users. If you’re hybrid or going through a long migration, there’s many scenarios where you want certain products or settings applied against the users and accounts based on where their mailbox is.

You could maintain that manually, but why do that when you can automate it!

Thankfully there’s two easy commands that will return accounts based on where they are – get-mailbox and get-remotemailbox. As long as you’re in Exchange Hybrid mode, you can run both of these commands against your local Exchange server.

Here’s the quick script I wrote up:

$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://exchange server name/Powershell -Authentication Kerberos
Import-PSSession $session
$remoteusers = Get-RemoteMailbox -resultsize unlimited
$onpremusers = Get-mailbox -resultsize unlimited
$remotegroup = "Exchange Online Users"
$onpremgroup = "Exchange OnPrem Users"

Get-ADGroup $remotegroup | Set-ADObject -clear member
Get-ADGroup $onpremgroup | Set-ADObject -clear member

foreach ($user in $remoteusers){
Add-ADGroupMember -Identity $remotegroup -Members $user.SamAccountName
}

foreach ($user in $onpremusers){
Add-ADGroupMember -Identity $onpremgroup -Members $user.SamAccountName
}

Remove-PSSession $Session

All I’m doing here is getting the two user types and putting them into variables – $remoteusers and $onpremusers. I’ve also used the group names as variables, so you can create whatever AD groups you like and put them into the $remotegroup and $onpremgroup variables.

Also I’m clearing out all members of the group before adding users, which means if someone gets migrated or leaves, they’ll be cleaned up from the old group properly.

Finally I’m going through the two users lists and using ‘foreach’ to add each user to the relevant group, using the SamAccountName value of each result to identify them.

It’s only a basic script, but you can easily add extra filters to the Get-Mailbox and Get-RemoteMailbox commands to do things such as only getting users from certain OUs.

This was tested on Exchange 2010, so if you get different results on Exchange 2013 or 2016 please let me know.

2 thoughts on “Exchange Online and Exchange On-Premises Security Groups

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.