Tuesday, December 14, 2021

Dynamic Distribution Group Changes Coming in 2022

According to a recent article by Tony Redmond, Microsoft is planning to modify the behavior of dynamic distribution groups in Exchange Online next year. The rollout is scheduled to begin in January and finish worldwide by the end of March.

The change is to when the members of dynamic distribution groups are calculated. Currently, dynamic distribution group queries are run every time someone sends a message to the group. While pre-canned queries are quick and cheap to resolve (performance-wise), queries that utilize custom filters can grow to be very complex and their resolution can have a performance impact on the Exchange transport service, introducing delivery delays. By "pre-resolving" dynamic distribution group queries once a day, the performance impact will be negligible and the reliability of the service will be improved.

So what's the downside? Well, by only calculating the membership once a day, your dynamic distribution groups will be a little less dynamic than before. But really, how often does membership in your dynamic distribution groups actually change throughout a single day? At my company, directory changes do occur almost hourly, but the vast majority of those changes occur to newly-created accounts, usually days or even weeks before the employee's first day of work. And even if a a relevant change occurs today, it's going to be less than one day for the associated dynamic distribution group member to be recalculated.

Currently, when you create a new dynamic distribution group or update the filter of an existing group, Exchange Online calculates the membership immediately. However, after this change goes into effect, it will take up to two hours for Exchange Online to calculate the membership of a new group or an existing group whose filters have been updated. This behavior will then be similar to how dynamic groups work in Azure AD.

There's no official word on whether this change will allow Outlook clients to view or expand dynamic distribution group memberships in real time (as they currently do with legacy distribution groups), but that would be a welcome feature, eliminating that "are they or are they not included?" question that I often get from our various executive assistants and members of the communications team.


Friday, February 12, 2021

Quick Hit: Subscribing Existing Members of a Microsoft 365 Group

Took me quite a while to find this solution so I'm just putting it out here so i can find it if I need it again.

The Problem: I re-purposed an O365 group in my Azure AD console, one that was already configured with the dynamic query I needed. Unfortunately, I didn't realize that, by default, members of O365 groups don't receive a copy of emails sent to the group in their personal mailbox. The messages just go to the group mailbox.

After doing some research, I reconfigured the O365 group to automatically "subscribe" new members, but that doesn't change the subscription status of the existing members. A lot of the "solutions" I found on the internet involved enabling the "Subscribe new members" flag and then removing all existing members and then adding them back to the group so that they would be subscribed. While that method probably works, it's not very elegant. There must be another way to accomplish my goal.

Turns out there is, and here it is: 

$group = Get-UnifiedGroup -Identity "Group_Name_or_Email_Address"

# Get list of all members
$members = Get-UnifiedGroupLinks -Identity $group.Name -LinkType Members

# Get list of all subscribers (a-ha!)
$subscribers = Get-UnifiedGroupLinks -Identity $group.Name -LinkType Subscribers

# Subscribe all members not subscribed
foreach ($member in $members) { 
    If ($member.Name -notin $subscribers.Name) {
        Write-Host "Adding $($member.Name)."
        Add-UnifiedGroupLinks -Identity $group.Name -LinkType Subscribers -Links $member.Name
    } else {
        Write-Host "$($member.Name) is already subscribed."
    }
}
# Done!

Almost all of the solutions I found online took the "remove everyone and then add them back again" approach, and maybe that's because that was the only solution at the time. Microsoft is always making changes and introducing new features and functionality, so maybe this PowerShell-based solution was not available until recently. Anyway, it works and it's a pretty simple solution.

Wednesday, December 16, 2020

Delete Inactive Accounts From Your Okta Org

Until a few months ago (as of this writing), I had an Automation Workflow in Okta that would delete Okta-mastered accounts that had not logged in for 2 years. That may sound like a long time to leave inactive accounts laying around, but we maintain accounts for former employees so they can get into Workday to retrieve their tax documents. Many of them will only sign in one time each year, but if an account goes unused for two years, they should be safe to delete without inconveniencing anyone.

Unfortunately, Okta recently changed the behavior of the Delete action in the automation workflow. Instead of setting the account status to DELETED, it deactivates them, turning the status to DEPROVISIONED, and the workflow is limited to just one Delete action so there's no way to actually delete the deactivated accounts in the workflow. To make matters worse, I have a powershell script that reactivates all deactivated accounts, so after the workflow deactivated the accounts, the powershell script turned around and reactivated them, even going so far as to sending activation emails to the accounts with legitimate email addresses. And THAT prompted calls and emails to the HR department, demanding to know why we continued to send them unsolicited emails. Needless to say, I deactivated that workflow as soon as I was made aware of the problem. I was quite busy at the time and so I didn't get around to finding another solution, until today. Well, yesterday, actually.

The solution has two parts. The first part involves the automation workflow. Instead of setting the account status to DELETED (DEPROVISIONED, actually), I modified it to set the status to SUSPENDED. In 5-6 years, I've used that status very rarely, so this seemed to be a great way to allow the workflow to identify dormant accounts and get them into some sort of container that I could then - and this is the second part - modify a copy of my reactivation powershell script to query Okta for all the users in the SUSPENDED status, and then delete them with an API call (two API calls, actually, since the first merely deactivates them, just as in the workflow).

Part 1: The Automation Workflow

The reactivation powershell script not only reactivates the accounts of former employees, but it also puts them into a special Okta group that assigns them to the Workday integration. The Automation Workflow also uses that Okta group to limit itself to just the former employees. The workflow is set to run at 5pm every day and look for any user that has been inactive for 730 days. If any former employee accounts meets that criteria, the account status is changed to SUSPENDED.

Part 2: The PowerShell Script

The powershell script will use the Okta API to query our org and return all accounts with a SUSPENDED status. It then loops through that array of accounts and makes two API calls to delete that account. As the script loops, information about each account is logged to a file, and when all the accounts have been processed, the script emails the log file to the designated email address. This gives us a record of which accounts were deleted, and when.

<#
.SYNOPSIS
    Okta_Purge_Inactive_Former_Associates.ps1 - Deletes suspended Okta accounts for former associates
    Created by Mike Koch on December 16, 2020
.DESCRIPTION
    Queries Okta for all SUSPENDED accounts, then deletes them
    Send email with all logged events/actions
.NOTES
    TO DO
    1. 
#>
[CmdletBinding()]
Param()

$api_token = "put_your_org_token_here"
$uri = "https://yourcompany.okta.com/api/v1/users?filter=status%20eq%20%22SUSPENDED%22"
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

$allusers = @()
$logfile = "c:\temp\Okta-Purge.log"
if (Test-Path -Path $logfile) {
    Remove-Item -Path $logfile -Force
}

function LogWrite {
    param ([string]$logstring)
    Add-Content $logfile -Value $logstring
}

# Query Okta using the URI specified above, page through the results to get all matching accounts
Do {
    $webrequest = Invoke-WebRequest -Headers @{"Authorization" = "SSWS $api_token"} -Method GET -Uri $uri
    $link = $webrequest.Headers.Link.Split("<").Split(">")
    $uri = $link[3]
    $json = $webrequest | ConvertFrom-Json
    $allusers += $json
} while ($webrequest.Headers.Link.EndsWith('rel="next"'))

if ($allusers.count -gt 0) {
    foreach ($usr in $allusers) {
        LogWrite "Deleting suspended user: $($usr.profile.login), $($usr.profile.displayname)"
        Write-Output "Deleting suspended user: $($usr.profile.login), $($usr.profile.displayname)"
# the first DELETE only DEACTIVATEs the account
        Invoke-WebRequest -Headers @{"Authorization" = "SSWS $api_token"} -Method Delete -Uri "https://yourcompany.okta.com/api/v1/users/$($usr.id)"
# the second DELETE actually DELETEs the account
        Invoke-WebRequest -Headers @{"Authorization" = "SSWS $api_token"} -Method Delete -Uri "https://yourcompany.okta.com/api/v1/users/$($usr.id)"
    }
    $MailMessage = @{
        To         = "SomeoneWhoCares@youremaildomain.com"
        From       = "OktaMaintenanceBot@youremaildomain.com"
        Subject    = "Report: Okta Former Employee Account Deletions"
        Body       = Get-Content $logfile -Raw
        BodyAsHtml = $false
        SmtpServer = "your.smtp.server"
    }
    Send-MailMessage @MailMessage
}

It's been a couple of months since the automation workflow broke. I opened a case with Okta and they acknowledged that there had been an unintended behavior change. The issue was escalated to the developers and the support case was closed. I'm sure they'll fix it eventually, but as a global retailer with thousands of employees, we have a lot of turnover so I need to keep up with the dormant account deletions. If for no other reason than to ensure that we have accurate counts the next time our contract is up for renewal. Even dormant accounts cost money.

Today's initial run of SUSPENDED users came to well over 14000. That got us caught up from the last couple of months, so subsequent runs should be much more reasonable, and finish much more quickly.

Tuesday, March 31, 2020

Don't Use O365 Portals To Set Permissions, Part 1 - FullAccess

I'm finding the O365 and Exchange Admin portals to be quite unreliable when it comes to viewing, setting, and changing permissions on Exchange objects. Retrieval times are slow and timeouts frequently occur. It's particularly frustrating when the current permissions finally appear and I quickly realize that they're not right, that some entries are missing. Our multi-geo environment undoubtedly makes this worse. It's just quicker and easier to use PowerShell, so I'm going to share the various commands and one-liners that I use on a regular basis to get the job done.

In almost all instances, a mailbox or a user can be referenced in a command parameter using their userprincipalname, email address or even their full name enclosed in double quotes. For example, you can use "jdirt@redneck.org", "JoeDirt@redneck.org" or "Joe Dirt" and Exchange will quickly and correctly locate and use the right object. There are always exceptions, but I haven't run into one yet. In the examples below, wherever you see "<mailboxaddress>" or "<useraddress>", you can substitute one of these IDs.

Mailbox Permissions - this is usually just a case of either adding or removing the FullAccess. Since completing our migration to Exchange Online, I'm finding that most of our shared mailboxes have a lot of stale permissions, be it unresolved SIDs or deleted O365 accounts.

The first step is to review the current permissions:

Get-MailboxPermission <mailboxaddress>

That works fine, but the output includes a lot of extra information you don't necessarily need or care about, and some of the stuff you do care about gets truncated. Here's what I use to get just the output I'm interested in.

Get-MailboxPermission <mailboxaddress> | where {$_.isinherited -eq $false -AND $_.user -notlike "NT AUTHORITY*"} | select user, accessrights | sort user

This removes the default and inherited permissions, and in most cases, the output doesn't get truncated. That final Sort helps when I need to copy multiple user strings to the clipboard so I can use Get-Clipboard to pull them into a variable.

The following commands handle the permissions changes.

Add-MailboxPermission <mailboxaddress> -AccessRights FullAccess -User <useraddress>

Remove-MailboxPermission <mailboxaddress> -AccessRights FullAccess -User <useraddress> -Confirm:$false

Next time, I'll cover the Send-As and Send On Behalf Of permissions.

Monday, December 30, 2019

Removing AD-Mastered Users From an Okta Group

When associates leave our company, their Active Directory accounts are automatically disabled, which in turn causes their Okta account to be deactivated. These former associates still need access to Workday, to get their paystubs and to retrieve their W-2 tax documents the following year. To facilitate access to Workday, their Okta accounts are reactivated (which turns them into Okta-mastered accounts) and added to a special Okta group that assigns them to the Workday integration.

Being a retailer, we hire a lot of temporary associates, particularly around the holidays, and quite a few of those are rehires from the previous season. And when a former associate is rehired, although a new AD account is created (because the old one has been deleted by this time), the new account usually has the same username and Workday number that they had previously. This is no big deal, but I recently discovered that most of these new AD accounts, once imported into Okta, were being automatically relinked to their old Okta accounts, the ones that were supposedly now Okta-mastered. And that's also not a big deal, since it requires no admin intervention due to name conflicts. The one negative is that these relinked accounts remain members of that special Okta group that assigns them to Workday. This doesn't cause a problem for the user, but since they also have an AD group membership that assigns them to Workday, membership in the Okta group is redundant. And it just annoys me, so I decided to write a script to remove them from the Okta group, since that's supposed to be for former associates only.

The following powershell script retrieves the entire list of users from the Okta group, then filters that list down to only the user profiles that have Active Directory as their credential provider. Those users are then deleted from the Okta group.

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$api_token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
$groupid = "xxxxxxxxxxxxxxxxxxxx"
$uri = "https://YOURORG.okta.com/api/v1/groups/$groupid/users?limit=1000"
Do {
    $webrequest = Invoke-WebRequest -Headers @{"Authorization" = "SSWS $api_token"} -Method GET -Uri $uri
    $link = $webrequest.Headers.Link.Split("<").Split(">")
    $uri = $link[3]
    $psobjects = $webrequest | ConvertFrom-Json
    $alum += $psobjects
} while ($webrequest.Headers.Link.EndsWith('rel="next"'))
$alumAD = @($alum | where-object {$_.credentials.provider.type -like "ACTIVE_DIRECTORY"})
if ($alumAD.count -gt 0) {
    foreach ($user in $alumAD) {
        $uri = "https://YOURORG.okta.com/api/v1/groups/$groupid/users/$($user.id)"
        $deleterequest = Invoke-WebRequest -Headers @{"Authorization" = "SSWS $api_token"} -Method DELETE -Uri $uri
    }
}

Sunday, December 29, 2019

Automating the Creation of Linked Mailboxes

Our regional IT teams have been delegated rights to create new user accounts in their own OUs. However, access to the on-premises Exchange org is limited to one or two org admins, as well as recipient admin rights for our Service Desk team.

Since there can sometimes be a significant delay between the creation of a new user account and the creation of that user's mailbox (mostly due to different timezones), I developed the following script to both reduce the load on the Service Desk and accelerate the creation of new mailboxes, which ultimately gives the regional IT teams more control over the provisioning process for their users.

The script is fairly specific to our environment, but hopefully the concepts will help others to create similar automation for their own systems. It currently runs as an hourly scheduled task. The regional IT teams simply need to add the string, "MailboxPlease" to the info attribute (on the Telephones tab) of the new user's account for the script to pick it up and create the linked mailbox.

<#
.SYNOPSIS
    NewLinkedMailbox - Creates a linked mailbox for accounts with MailboxPlease in the info attribute
    Created by Mike Koch on October 29, 2019
.DESCRIPTION
    Queries USERDOMAIN for user accounts that have 'MailboxPlease' in the 'info' attribute
        - this attribute is populated by the regional IT teams, which have been delegated rights to create user accounts in their own OUs
    Creates a matching account in the RESOURCEDOMAIN, in the appropriate region OU
    Sets the Company attribute on the mailbox account, to ensure that the proper email address policy is applied
    Creates the linked mailbox, then copies the primary smtp address back to the user's account in USERDOMAIN
    Clears 'MailboxPlease' from the info attribute
.NOTES
    Assumes the account running this script has sufficient rights to do the following:
        1. Read user properties in USERDOMAIN
        2. Create user accounts in RESOURCEDOMAIN
        3. Create linked mailboxes in the on-premises Exchange org
        4. Write user properties in USERDOMAIN (to write the primary smtp address back to the user's account)
#>
[CmdletBinding()]
Param()

$USERDOMAINDC = "dc1.USERDOMAIN.local"
$RESOURCEDOMAINDC = "dc1.RESOURCEDOMAIN.local"

###
# Query USERDOMAIN for enabled accounts containing "MailboxPlease" in the info attribute
###
$mbxrequests = @(Get-ADUser -Filter { enabled -eq $true -AND info -like "*MailboxPlease*" } -Server $USERDOMAINDC -SearchBase "ou=All Users,dc=USERDOMAIN,dc=local" -Properties givenname, sn, title, description, department, office, company, manager)

if (!$mbxrequests) {
    Write-Verbose "No mailbox requests detected."
}
else {
    foreach ($mbx in $mbxrequests) {
        Write-Verbose "Attempting mailbox creation for $($mbx.Name)..."
        $resAccountParms = @{ }
        $resAccountParms.Add("displayName", $mbx.Name)
        $resAccountParms.Add("userprincipalname", "$($mbx.SamAccountName)@COMPANYNAME.com")
        switch -Wildcard ($mbx.DistinguishedName) {
            "*Australia Associates*" { 
                $path = "ou=Australia,ou=LinkedMailboxAccounts,dc=RSEOURCEDOMAIN,dc=local"
                $resAccountParms.Add("company", "COMPANYNAME Australia") # required to trigger custom email address policy
            }
            "*Canada Associates*" { 
                $path = "ou=Canada,ou=LinkedMailboxAccounts,dc=RESOURCEDOMAIN,dc=local"
                $resAccountParms.Add("company", "COMPANYNAME Canada") # required to trigger custom email address policy
            }
            "*France Associates*" { 
                $path = "ou=France,ou=LinkedMailboxAccounts,dc=RESOURCEDOMAIN,dc=local"
                $resAccountParms.Add("company", "COMPANYNAME France") # required to trigger custom email address policy
            }
            "*Germany Associates*" { 
                $path = "ou=Germany,ou=LinkedMailboxAccounts,dc=RESOURCEDOMAIN,dc=local"
                if ($mbx.company) { $resAccountParms.Add("company", $mbx.company)}
            }
            "*Ireland Associates*" { 
                $path = "ou=Ireland,ou=LinkedMailboxAccounts,dc=RESOURCEDOMAIN,dc=local"
                if ($mbx.company) { $resAccountParms.Add("company", $mbx.company)}
            }
            "*Italy Associates*" {
                $path = "ou=Italy,ou=LinkedMailboxAccounts,dc=RESOURCEDOMAIN,dc=local"
                if ($mbx.company) { $resAccountParms.Add("company", $mbx.company)}
            }
            Default {
                $path = "ou=LinkedMailboxAccounts,dc=RESOURCEDOMAIN,dc=local"
                if ($mbx.company) { $resAccountParms.Add("company", $mbx.company)}
            }
        }
        if ($mbx.givenname) { $resAccountParms.Add("givenName", $mbx.GivenName) }
        if ($mbx.sn) { $resAccountParms.Add("sn", $mbx.sn) }
        if ($mbx.Department) { $resAccountParms.Add("department", $mbx.Department) }
        if ($mbx.description) { $resAccountParms.Add("description", $mbx.description) }
        if ($mbx.Title) { $resAccountParms.Add("title", $mbx.Title) }
        if ($mbx.office) { $resAccountParms.Add("physicalDeliveryOfficeName", $mbx.office) }
        $resAccountParms.Add("extensionAttribute1", "migrate.me")  # triggers migration script

        ### Let's see if we can locate this user's manager's mailbox account in RESOURCEDOMAIN
        if ($mbx.Manager) {
            $mgrsam = (Get-ADUser $mbx.Manager -Server $USERDOMAINDC).SamAccountName
            $resAccountParms.Add("Manager", (Get-ADUser $mgrsam -Server $RESOURCEDOMAINDC).DistinguishedName)
        }

        ### Make sure this samaccountname doesn't exist in RESOURCEDOMAIN
        if (!(Get-ADUser -Filter "samaccountname -eq '$($mbx.SamAccountName)'" -Server $RESOURCEDOMAINDC)) {
            Write-Verbose "Creating RESOURCEDOMAIN account for $($mbx.Name)..."
            New-ADUser -Name $mbx.Name -SamAccountName $mbx.SamAccountName -Enabled $FALSE -Path $path -Server $RESOURCEDOMAINDC -OtherAttributes $resAccountParms
            $resacct = Get-ADUser $mbx.SamAccountName -Server $RESOURCEDOMAINDC
            if ($resacct) {
                Write-Verbose "Creating linked mailbox for $($mbx.Name)..."
                $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://OnPremExchangeServer/powershell/ -Authentication Kerberos -AllowRedirection
                Import-PSSession $Session -CommandName Enable-Mailbox
                Enable-Mailbox -Identity $resacct.DistinguishedName -DomainController $RESOURCEDOMAINDC -Alias $resacct.SamAccountName -LinkedMasterAccount $mbx.DistinguishedName -LinkedDomainController $USERDOMAINDC
                Get-PSSession | Remove-PSSession

                ### copy email address to the USERDOMAIN account
                $email = (Get-ADUser $mbx.SamAccountName -Server $RESOURCEDOMAINDC -Properties mail).mail
                Set-ADUser $mbx.SamAccountName -Server $USERDOMAINDC -EmailAddress $email -Clear info
            } else {
                Write-Verbose "Creation of RESOURCEDOMAIN account failed $($mbx.SamAccountName)"
            }
        }
        else {
            Write-Verbose "Samaccountname already exists in RESOURCEDOMAIN ($($mbx.SamAccountName))."
        }
    }
}
Write-Verbose "Finished."

Automate the Migration of Linked & Shared Mailboxes

Our current environment consists of Exchange 2010 on-premises and Exchange Online, in hybrid mode with centralized mail flow enabled, and Azure AD Connect synchronizing everything. We have two forests, each with user accounts (result of a merger and a CIO who didn't want to rock the boat and force everyone in one forest to migrate). Both forests had Exchange 2003 at the time, but when we upgraded to 2007 we consolidated down to one Exchange org. Users in the same forest as Exchange have normal user mailboxes, while users in the other forest require linked mailboxes. And it's been that way for more than 10 years. Office 365 and Exchange Online came along a few years ago, but we just got around to migrating all user mailboxes last year.

Although new mailboxes for users in the forest with Exchange can easily be created in Exchange Online by running the Enable-RemoteMailbox command, the users in the other forest still have to be created on-premises as linked mailboxes, and then migrated to Exchange Online. We've also had some challenges with creating shared mailboxes, so those get created on-premises as user mailboxes, then converted to shared mailboxes and THEN migrated to Exchange Online.

The powershell script you see below is my solution to automating the migration of those linked and shared mailboxes. This script runs every hour as a scheduled task, queries the on-premises Exchange for new linked or shared mailboxes, and if any are found, each is submitted in its own migration batch. The only issue I encountered was one of timing - the migration batches would fail if they got submitted before Azure AD Connect had synchronized the on-premises objects up into Exchange Online. I mistakenly thought that the "-StartAfter" parameter of New-MigrationBatch command would allow me to delay the start of the migration. Turns out it only delays the actual data movement, but Exchange Online was starting the object-matching prep work as soon as the batch was submitted. To solve that problem, I added a bit of logic to delay submission of the migration batch until at least one hour after the whenMailboxCreated timestamp, which gives Azure AD Connect plenty of time to get everything in place, and I've had no failures since.

<#
.SYNOPSIS
    MigrateMailboxes - Migrates linked and shared mailboxes to Exchange Online
    Created by Mike Koch on December 20, 2019
.DESCRIPTION
    Remote powershell to on-premises Exchange
        Query Exchange for linked and/or shared mailboxes to migrate
    Remote powershell to Exchange Online
        Submit migration batch request with CSV file
.NOTES
    DEPENDENCIES
    1. Functions-PSStoredCredentials.ps1 - http://practical365.com/blog/saving-credentials-for-office-365-powershell-scripts-and-scheduled-tasks
        - contains functions to store and retrieve encrypted credentials from the local file system
        - required so that script can run unattended
    
    ASSUMPTIONS
    1. Assumes the account running this script has admin rights in the on-premises Exchange environment, as well as Account Operator
        rights in the linked domain.
    
    TO-DO
    1. Integrate my linked mailbox creation script, to result in one script that handles everything, easier to maintain
    #>

[CmdletBinding()]
Param()

$linkedDC = "dc1.userdomain.local"  # needed only to add linked mailbox users to O365 licensing groups

## IMPORTANT: encrypted credentials can only be retrieved by the same account that was used to encrypt them
## AND must be on the same machine where they were encrypted
. "C:\Scripts\Functions-PSStoredCredentials.ps1"
$cred = Get-StoredCredential -UserName globaladmin@yourcompany.onmicrosoft.com

##### Connect to on-premises Exchange, import only the commands we plan to use
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://OnPremExchangeServer/powershell/ -Authentication Kerberos -AllowRedirection
Import-PSSession $Session -CommandName Get-Mailbox, Set-Mailbox

##### Build a list of mailboxes to migrate
## Some older shared mailboxes stay on-premises, so we'll set a date variable to limit our query to recently created mailboxes
$SharedMailboxThreshold = (Get-Date).AddDays(-30)
## A separate script creates linked mailboxes and sets extensionAttribute1 to "migrate.me"
$MailboxesToMigrate = @(Get-Mailbox | Where-Object {$_.RecipientTypeDetails -like "LinkedMailbox" -AND $_.CustomAttribute1 -like "migrate.me"})
## Returns recently created shared mailboxes that are not already being migrated (see line 90, below)
$MailboxesToMigrate += @(Get-Mailbox | Where-Object {$_.RecipientTypeDetails -like "SharedMailbox" -AND $_.whenMailboxCreated -gt $SharedMailboxThreshold -AND $_.CustomAttribute1 -notlike "migration in progress"})

if ($MailboxesToMigrate.count -gt 0) {
    ##### Initiate remote powershell connection to Exchange Online, import only the commands needed to submit a migration batch
    $exo = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $cred -Authentication Basic -AllowRedirection
    Import-PSSession $exo -CommandName Get-MigrationEndPoint, New-MigrationBatch
    $MigrationEndpointOnPrem = Get-MigrationEndpoint -Identity owa.on-prem-endpoint.com
    
    foreach ($mbx in $MailboxesToMigrate) {
        ## don't try to migrate a mailbox until it's at least one hour old
        ## this ensures that Azure AD Connect has had enough time to replicate the object to Azure and Exchange Online
        if ((New-TimeSpan -Start $mbx.whenMailboxCreated -End (Get-Date).AddHours(-1)) -gt 0) {
            $mbx | Select-Object @{Name="EmailAddress";Expression={$_.primarysmtpaddress}} | Export-Csv "c:\temp\mbx.csv" -NoTypeInformation

            ## use the mailbox name as the migration batch name, but make sure it doesn't exceed the 64-char limit
            ## very unlikely, but costs almost nothing to do
            $batchname = "$($mbx.displayName)"
            if ($batchname.Length -gt 60) {
                $batchname = $batchname.Substring(0,60)
            }

            ###### Submit the migration batch
            Write-Verbose "Submitting migration batch request..."
            New-MigrationBatch -Name $batchname `
                -SourceEndpoint $MigrationEndpointOnPrem.Identity `
                -TargetDeliveryDomain yourcompany.mail.onmicrosoft.com `
                -CSVData ([System.IO.File]::ReadAllBytes("c:\temp\mbx.csv")) `
                -NotificationEmails "EmailAdmin@yourcompany.com" `
                -AutoStart `
                -AutoComplete

            switch ($mbx.RecipientTypeDetails) {
                "LinkedMailbox" {
                    # clear the migrate.me string from customattribute1
                    Set-Mailbox $mbx.primarySmtpAddress -CustomAttribute1 $null
                    ## we want to assign an EXO license to the user account in the linked domain (not the mailbox account)
                    ## LinkedMasterAccount contains the owner's account, in domain/username format
                    ## we just need to grab the username portion, which is the samaccountname in the linked domain
                    $sam = $mbx.LinkedMasterAccount.split("\")[1]
                    ##### Assign Office Pro Plus and Exchange Online feature licenses to the mailbox owner
                    ## Assumes use of group-based licensing, which requires an Azure AD Premium subscription
                    Add-ADGroupMember -Identity "O365 Exchange Online (E5)" -Members $sam -Server $linkedDC
                    Add-ADGroupMember -Identity "O365 Office Pro Plus (E5)" -Members $sam -Server $linkedDC
                }
                "SharedMailbox" {
                    ## set extensionAttribute1 to avoid adding this mailbox to future migrations (see line 44, above)
                    Set-Mailbox $mbx.primarySmtpAddress -CustomAttribute1 "migration in progress"
                }
                Default {}
            }
        }
    }
    Get-PSSession | Remove-PSSession
}

Write-Verbose "Finished."