Blog

  • Migrating 150,000 distribution groups to Exchange Online as a one-person team

    In short: I moved roughly 150,000 on-premises distribution groups and mail-enabled security groups to Exchange Online – about 80,000 simple ones and 70,000 nested ones – as a one-person team. The core trick is simple: build a prefixed copy in the cloud, retire the original through directory sync, then reveal the copy under the original name. Everything around it – discovery, data quality, dependencies and communication – is what made it work.

    The starting point

    The organisation ran hybrid Exchange, with every distribution group created and managed in on-premises Active Directory and synced to the cloud. The goal: groups mastered directly in Exchange Online, on-premises dependencies removed, and proper lifecycle management with owners and expiry dates. The project ran from autumn 2024 to spring 2026.

    What made it hard was not the number of groups, but how they were used:

    • Deep nesting in both directions – groups inside groups inside groups, and the same group sitting in several parents.
    • Mixed types everywhere – distribution groups and mail-enabled security groups nested in each other, with members ranging from users and contacts to other groups and even computer accounts.
    • Dependencies across the platform – the same groups granted access to SharePoint sites and Teams, Power BI workspaces, Azure resources, app registrations and Power Apps.
    • Internal applications using distribution groups for authorisation – they shouldn’t, but many did.
    • On-premises leftovers – groups containing on-premises mailboxes, room-booking policies and mailbox forwarding that pointed at groups.

    Discovery first: a database, not a spreadsheet

    Before migrating a single group, I spent a long time on inventory. With this many objects and relationships, spreadsheets stop working quickly, so I built a SQL Server database with dozens of tables and views, refreshed regularly by PowerShell import jobs.

    Discovery: on-premises AD, Exchange Online, Entra ID, SharePoint and Teams, Power BI and Azure apps feed one SQL Server database, which drives the Power BI report, Power Automate communication and the migration scriptsDiscovery: everything flows through one databaseRefreshed regularly by PowerShell import jobsOn-premises ADExchange OnlineEntra IDSharePoint & TeamsPower BIAzure apps & Power AppsSQL Server databasedozens of tables and viewsInventorygroups, members, owners, nestingExclusionsempty, unsynced members, appsReadinesssimple / complex ready viewsPre-checksduplicates, routing, sendersImpactsites, workspaces, apps, rolesMigrationschedule, status, log, backupPower BI report~10 pages: status, waves, dependenciesPower Automateowner emails, EN/DE templatesMigration scriptsread work lists, write status
    Every source system fed one database; the report, the owner emails and the migration scripts all read from it.

    The database held the full picture:

    • Inventory – on-premises and cloud groups, members, owners, contacts, accepted domains, and the nesting structure, including which groups were leaves and who their parents were.
    • Exclusions – empty groups, groups with members that weren’t synced to the cloud, application groups and explicit exclusions.
    • Readiness views – “ready to migrate” lists for simple and complex groups, which the migration scripts read directly.
    • Pre-migration checks – duplicate addresses and names, groups with several routing addresses, sender restrictions that pointed at other groups, groups sitting under non-mail parents.
    • Impact queries – which groups granted access to SharePoint sites, Teams, Power BI workspaces, app registrations and Power Apps.
    • Migration tables – schedule, status, a log of every step, and backups of the original objects.

    On top of it, a Power BI report of around ten pages showed the status before and after, progress per wave, and the dependencies per service. It was the single place to answer “where are we?” – for me and for management.

    Cleanup and communication

    The cheapest group to migrate is the one you delete. Before the migration, group owners were asked to review their groups and remove what was no longer needed. About 8k groups were deleted before migration.

    With tens of thousands of owners, the emails had to be automated too. I built Power Automate flows that read the list of affected groups, grouped them by owner, and sent each owner one email with a table of all their groups – in English and German, from a shared mailbox, with a short delay between messages to stay within sending limits. Different templates covered different situations: advance notices, post-migration notices, and special messages for owners of mail-enabled security groups whose groups were used in SharePoint.

    Migration waves were grouped by domain and by owner, so each owner received one message per wave instead of one per group, and runs happened outside business hours.

    The core idea: clone, retire, reveal

    A group synced from on-premises can’t simply be converted into a cloud-managed group. So each group went through three phases: a new copy is built in Exchange Online next to the original, the original is retired through directory sync, and the copy then takes over the original’s name and addresses.

    Clone, retire, reveal: what happens to the original group, directory sync and the new Exchange Online group in each of the three migration phasesClone, retire, reveal: one group through the three phasesWhat happens to each object, phase by phaseOn-premises ADDirectory syncExchange OnlinePHASE 1 · CLONEPHASE 2 · RETIREPHASE 3 · REVEALOriginal group, stillsynced to the cloudOriginal renamed with decom_ prefix,hidden, excluded from syncContact placeholder created withthe original addresses → cloud groupContact nested into on-prem parentsOriginal kept as decom_ backupfor the hypercare period;contact keeps routing on-premOriginal group syncsas usualNext sync cycle sees theexclusion and deletes thecloud copy of the originalScript polls Exchange Onlineuntil the original is goneNew cloud group, every addressprefixed with MIG_, hiddenSettings, owners, senders copiedOriginal legacyExchangeDN → X500Routing address addedMembers copied (10k limit)Synced original disappears;the clone keeps running,still prefixed and hiddenPrefixes removedShown in the address bookMarked as cloud-managedHelper contacts removed
    What happens to the original, to directory sync and to the new cloud group in each phase.

    Phase 1 – Clone

    • Create a new group in Exchange Online with a prefix (here MIG_) on its name, alias, display name and every address, so it can exist next to the still-synced original without conflicts. It stays hidden from the address book.
    • Copy the settings: owners, moderation, sender restrictions, mail tips including translations, custom attributes and notes.
    • Copy the original’s legacyExchangeDN as an X500 address. This is the single most important routing detail: without it, replies to old messages and cached Outlook autocomplete entries bounce.
    • Add the tenant routing address (alias@tenant.mail.onmicrosoft.com). Groups created in the cloud don’t get one automatically, but the on-premises contact from phase 2 needs it as its target.
    • Copy the members – see the 10,000-entry limit below.
    • Fix the data along the way: groups whose owner was empty or pointed at an admin role group got a placeholder owner, and owners and allowed senders were resolved to real mailboxes, with anything else dropped and logged.
    # Phase 1 – give every address a prefix, so the clone can coexist with the synced original
    $prefix = "MIG_"
    $smtp = $source.EmailAddresses | Where-Object { $_ -match '^smtp:' } |
            ForEach-Object { $_ -replace ':', ":$prefix" }
    
    # Keep the original legacyExchangeDN as an extra X500 address – this is what keeps
    # replies to old messages and Outlook autocomplete working after the move
    $x500 = @($source.EmailAddresses | Where-Object { $_ -match '^x500:' }) +
            "x500:$($source.LegacyExchangeDN)"
    $x500 = $x500 | ForEach-Object { $_ -replace 'Recipients/cn=', "Recipients/cn=$prefix" }
    
    Set-DistributionGroup -Identity $clone.ExchangeObjectId -EmailAddresses ($smtp + $x500)

    The members need two steps, because Update-DistributionGroupMember accepts at most 10,000 entries per call – the same limit I wrote about in the post on dynamic distribution groups:

    $members = Get-DistributionGroupMember -Identity $source.ExchangeObjectId -ResultSize Unlimited |
               Select-Object -ExpandProperty ExchangeObjectId
    
    # Update-DistributionGroupMember accepts at most 10,000 entries per call
    Update-DistributionGroupMember -Identity $clone.ExchangeObjectId -Members $members[0..9999] -Confirm:$false
    
    # Anything above that goes one by one – one round trip per member, slow but reliable
    if ($members.Count -gt 10000) {
        foreach ($m in $members[10000..($members.Count - 1)]) {
            Add-DistributionGroupMember -Identity $clone.ExchangeObjectId -Member $m
        }
    }

    Phase 2 – Retire

    • Back up the original first: attributes and the full member list, to a file and to the database. Not every on-premises member existed in the cloud, so this was the only complete record.
    • For distribution groups: rename the original with a decom_ prefix on every unique attribute, hide it from the address book, and set the attribute the sync rules use to exclude it. The next sync cycle deletes its cloud copy.
    • For mail-enabled security groups: mail-disable the group on-premises, keep it as a plain security group with “(Security Group)” added to its name, and back up its mail attributes as JSON.
    • Create an on-premises mail contact with the original addresses and X500, pointing at the routing address, hidden from the address book. An extension attribute holds a small JSON object that links the on-premises contact, the cloud group and the corporate directory entry. Each contact also gets an expiry date, randomised between 13 and 18 months, so renewals don’t all land in the same week.
    • Nest the contact into every mail-enabled parent group on-premises, so those parents keep delivering to the migrated group. Object of type contact can only be member of a group by updating that group’s [Member] attribute.
    ...
    $contactGadObj =     get-adobject -filter "objectclass -eq 'contact' -and mail -eq '$($contactDefinition.origGroupMail)'" ...
    $tempContactGadObj = get-adobject -filter "objectclass -eq 'contact' -and mail -eq 'temp_$($contactDefinition.origGroupMail)'" ...
    
    ...
    
    Set-ADGroup -Identity $parentGrpObj `
                        -Server $parentBasicObj.canonicalname.substring(0,14) `
                        -Add @{member=$contactGadObj.ObjectGUID,$tempContactGadObj.ObjectGUID} `
                        -Credential $onPremCredential `
                        -Confirm:$confirm `
                        -WhatIf:$whatif `
                        -ErrorAction Stop
    ...

    Phase 3 – Reveal

    • Poll Exchange Online until the original group has disappeared – proof that the sync has run.
    • Remove the prefixes from the new group, show it in the address book and mark it as cloud-managed, so the lifecycle automation adopts it.
    • Remove helper contacts that were only needed during the transition.

    Between the original disappearing and the prefixes being removed, mail to the group can bounce. Running the waves outside business hours kept that window harmless.

    Nested groups: bottom-up, one layer at a time

    About 70,000 groups contained other groups or were members of other groups. Migrating a parent before its children breaks membership, so the complex groups moved from the bottom up, with each layer completed before the next one started.

    What users see during the migration of nested groups: before, all groups are legacy and synced; during, migrated children are represented in the legacy parent by temporary contacts that route mail to the new cloud groups; after, all groups live in the cloud and permanent on-premises contacts only route mailWhat users see during the migration of nested groupsOne parent group with two children, before, during and after1 · BEFOREEverything is legacy and syncedON-PREMISES ADEXCHANGE ONLINEdirectory sync2 · DURINGChildren migrated, parent still legacyON-PREMISES ADEXCHANGE ONLINEdirectory sync3 · AFTEREverything lives in the cloudON-PREMISES ADEXCHANGE ONLINEnot syncedParentChild 1Child 2Parent (synced)Child 1 (synced)Child 2 (synced)ParentChild 1 · temp contactChild 2 · temp contactParent (synced)Temp contactTemp contactChild 1Child 2mail routingParent · contactChild 1 · contactChild 2 · contactpermanent,not synced:routing onlyParentChild 1Child 2Legacy groupSynced copyCloud groupMail contactMail routing
    What users saw for one parent group: before, while its children had already moved, and after the parent followed them.
    • When a leaf group migrates, its contact takes its place inside every on-premises parent.
    • When the parent migrates later, its members include those contacts. The script reads the JSON link on each contact and adds the real cloud group as a member instead.
    • Mail-disabled security groups had to be removed from their distribution-list parents, otherwise they blocked those parents from migrating.
    • Readiness views in the database checked each layer before it ran: local mailboxes in the hierarchy, security groups inside it, and parents that weren’t mail-enabled.

    Dependencies: what breaks when a group is recreated

    A new group means a new object ID. Anything that granted access to the old group by ID loses that access: SharePoint and Teams permissions, Power BI workspace roles, Azure role assignments, app registrations and Power Apps sharing. Distribution groups should never be used for authorisation, but many were – especially the mail-enabled security groups.

    • The impact queries listed, per group, which sites, workspaces, apps and roles depended on it, together with the owner and their division.
    • Owners were told in advance, with the affected resources listed in their email.
    • For mail-enabled security groups, we compared two methods and chose the one that keeps a single mail-enabled security group in the cloud, so it can be used for authorisation again.
    • Because of the sheer complexity of how SharePoint permissions are applied (as roles, as permissions to content, links, etc.) I relied on the site collection admins to restore the permissions.

    Built to be rerun

    Running the same scripts tens of thousands of times means things will fail halfway through – throttling, replication delays, odd data. The scripts were built to be restarted at any point:

    • Every phase reads its work list from the database and writes the group’s status after each step, so a run can stop and resume anywhere.
    • Every step is logged to a database table and a transcript file.
    • Calls to Exchange Online and Active Directory are retried with pauses, to ride out throttling and replication delays.
    • “Already exists” and “address already in use” on a rerun are treated as success, which makes each phase idempotent.
    • Unexpected errors pause the run instead of guessing. A person decides.

    Lessons learned

    • Discovery is the project. Most of the time went into understanding the data, not migrating it.
    • Never trust attributes as they are. Owners, allowed senders and addresses all needed validating and resolving before they could be copied.
    • Keep the legacyExchangeDN. Copying it as an X500 address is what makes a migrated group invisible to users.
    • Find the groups used for authorisation early. They carry the real risk, not the mail flow.
    • Be careful with automated deletes. A cleanup step meant for the old group once deleted a new one. It was removed from the process, not patched.
    • Communicate per owner, not per group. One clear email per owner per wave, in their language.
    • A one-person team needs automation everywhere. The database, the scripts, the emails and the report all fed each other.

    Facing a similar migration?

    I’m happy to talk through your environment and what would work for it. Get in touch.

  • Migrating dynamic distribution groups to Exchange Online: why we ended up with Microsoft 365 groups

    In short: Exchange Online dynamic distribution groups couldn’t use the attributes our filters relied on, and scripting static groups didn’t scale. Microsoft 365 groups with Entra ID dynamic membership did – once we tuned them to behave like distribution lists.

    Three paths for on-premises dynamic distribution groups: Exchange Online dynamic DLs (dead end), scripted regular DLs (too slow), Microsoft 365 groups with Entra dynamic membership (adopted) Three paths for on-premises dynamic distribution groups Hybrid Exchange → Exchange Online, a few dozen very large groups START On-premises dynamic DLs Recipient filters on AD attributes OPTION 1 Rebuild as Exchange Online dynamic DLs Filter attributes exist on-premises but aren’t synced to Exchange Online ✕ Dead end OPTION 2 Script membership of regular DLs Max 10,000 entries per call, one round trip per change: too slow ✕ Too slow OPTION 3 Microsoft 365 groups + Entra dynamic membership Rules on Entra ID or synced attributes · needs Entra ID P1 per member ✓ Adopted
    The three options we tested, and where each one ended.

    The challenge

    On a large-scale migration project, the goal was to move all email distribution groups from a hybrid Exchange setup fully to the cloud. The regular groups also were not exactly straightforward, however, that is a different story. The question was what to do with the dynamic ones.

    The customer had a few dozen very large groups of the native Exchange dynamic distribution type. On-premises, their membership is evaluated each time a message is sent to the group. In Exchange Online, the membership list is stored and refreshed once every 24 hours, which is more predictable and faster for delivery. So the obvious idea was to rebuild them in Exchange Online.

    Dead end 1: rebuilding them as Exchange Online dynamic groups

    Exchange Online recipient filters can only use Exchange recipient properties: standard ones such as Department, Company or City, plus CustomAttribute1–15 and the multi-valued ExtensionCustomAttribute1–5. The attributes the business actually wanted to filter on – cost centre, division, business unit, employee type – lived in the on-premises directory and reached Entra ID only as directory extension attributes. Exchange Online never saw them.

    Making them usable would have meant new replication rules to copy them into Exchange custom attributes. And the standard attributes were no shortcut: the Company attribute alone held dozens of variants of what was effectively the same business. A filter built on that is long, fragile and slow.

    On top of that, recipient filters have their own limits: pre-canned filters only support -and, and -like doesn’t accept a wildcard at the start of a value.

    Dead end 2: maintaining regular groups with a script

    Next, I tried maintaining the members of regular distribution groups in Exchange Online programmatically. This hit two walls:

    • A hard limit. Update-DistributionGroupMember replaces the whole member list, and its -Members parameter accepts a maximum of 10,000 entries (Microsoft Learn). Our biggest groups were larger than that.
    • Speed. The fallback – read the current members, compare with the new candidates, then add and remove the differences with Add-DistributionGroupMember and Remove-DistributionGroupMember – meant one round trip to Exchange Online per change. With tens of thousands of members, enumerating and updating the groups was far too slow and consumed too many resources.

    What worked: Microsoft 365 groups with Entra ID dynamic membership

    Microsoft 365 groups can use Entra ID to update their members dynamically, based on user attributes – both standard ones and the directory extension attributes synced from on-premises. That removed the attribute problem and the scripting overhead in one go. The rule syntax is also far richer than Exchange recipient filters.

    Testing was a bumpy road, because Microsoft 365 groups are not distribution lists. Each one comes with a group mailbox, a SharePoint site, OneNote and Planner, and several defaults work against the “distribution list” experience. In the end the concept was solid and performed very well. It took end users some getting used to, but it was accepted as a working solution.

    How we provisioned them

    Creation is a two-step process, because some settings exist only in Microsoft Graph and others only in Exchange Online. A simplified version:

    # Step 1 – Microsoft Graph PowerShell: create the group
    $params = @{
        displayName                   = "All contractors"
        mailNickname                  = "all-contractors"
        groupTypes                    = @("Unified", "DynamicMembership")
        mailEnabled                   = $true
        securityEnabled               = $false
        membershipRule                = '(user.employeeType -eq "Contractor") -and (user.accountEnabled -eq true)'
        membershipRuleProcessingState = "On"
        resourceBehaviorOptions       = @("WelcomeEmailDisabled", "HideGroupInOutlook",
                                          "SubscribeMembersToCalendarEventsDisabled", "CalendarMemberReadOnly")
        "owners@odata.bind"           = @("https://graph.microsoft.com/v1.0/users/<owner-object-id>")
    }
    $group = New-MgGroup -BodyParameter $params
    # Step 2 – Exchange Online PowerShell: make it behave like a distribution list
    Set-UnifiedGroup -Identity $group.Id `
        -AutoSubscribeNewMembers:$true `
        -HiddenFromAddressListsEnabled:$false `
        -ModerationEnabled:$true `
        -ModeratedBy "moderator1@contoso.com", "moderator2@contoso.com"

    Creating the group through Graph has a useful side effect: no Team is created, so the group stays a plain mail-enabled group.

    Settings that make a Microsoft 365 group behave like a distribution list

    • resourceBehaviorOptions at creation: WelcomeEmailDisabled (no welcome email to thousands of people), HideGroupInOutlook, SubscribeMembersToCalendarEventsDisabled and CalendarMemberReadOnly.
    • AutoSubscribeNewMembers: without it, messages land only in the group mailbox and members never see them in their own inbox. It can’t be set in the initial Graph create request, so set it straight afterwards.
    • Hidden from Outlook, but not from the address book. HideGroupInOutlook also hides the group from the global address list, so set HiddenFromAddressListsEnabled back to $false if people should be able to find it.
    • Moderation instead of accepted senders. With tens of thousands of recipients, someone must approve what gets sent. Moderation can only be configured in Exchange Online (Set-UnifiedGroup -ModerationEnabled -ModeratedBy), not through Graph. We chose it over an accepted-senders list, because accepted senders couldn’t cover external senders.
    • Security-enabled groups can’t hide their membership. If a group also grants access to resources, HiddenMembership visibility isn’t available.

    The “where is my copy?” gotcha

    Senders who are members of the group don’t get a copy of their own message by default – unlike with a classic distribution list. This isn’t a group setting: it’s controlled per sender with EchoGroupMessageBackToSubscribedSender (Set-MailboxMessageConfiguration), or by each user in Outlook on the web under Settings › Groups. Plan to set it for the senders who need it, or tell users where to find it.

    Writing membership rules that perform

    • Prefer -in over a chain of -or conditions.
    • Prefer -eq and -startsWith over -match and -contains wherever you can.
    • After creating or changing a rule, check the processing status (in the Entra admin center, or via the membershipRuleProcessingStatus property in Graph beta) before telling the requester the group is ready.
    • Expect a human step: requesters describe the audience in words, and someone has to translate that into attributes and values that actually exist in the directory.

    Operational gotchas

    • Licensing. Dynamic membership in Entra ID requires a Microsoft Entra ID P1 licence for each unique user who is a member of one or more dynamic groups. Check this before you commit.
    • Expiration. With a group expiration policy (e.g. 365 days), owners get reminders and must renew unused groups – otherwise they disappear. Administrators can renew them too, e.g. with Invoke-MgRenewGroup.
    • Group mailbox. It has a fixed quota and no archive, so retention policies are the only cleanup tool.
    • Management split. The groups don’t appear in the Exchange admin center as distribution lists, and the membership rule can only be changed in Entra ID. Decide up front which team owns which part.

    Want the details?

    I’m happy to share more about the provisioning parameters and the order of steps that worked. Get in touch.