M365 Cross Tenant Migration | Part II

Tenant Migration
Reading Time: 3 minutes

As stated before in M365 Cross Tenant Migration | Part I Microsoft have released the 1st of November 2022 the option to migrate userdata between two M365 tenants. Therefore you need to create an App Registration and an Organizational Relationship between the two tenants. If you have not done yet part I, you will not be able to follow below.

Users Source Tenant

Before users can be migrated to the GetToTheCloudTarget.onmicrosoft.com tenant, they need to be created and provided with the necessary information. This information can be found in the GetToTheCloudSource.onmicrosoft.com tenant.

We need PowerShell to get that information, so let’s start a PowerShell command window

#Exchange Online Management v3 Powershell module
Install-Module -Name ExchangeOnlineManagement -RequiredVersion 3.0.0 -Force

#Connect to Exchange Online from SOURCE tenant
Connect-ExchangeOnline

First we get all the members of the security group we created in previous post

$sourceGroup = "Users to Migrate"
$Members = Get-DistributionGroupMember $sourceGroup -WarningAction SilentlyContinue | Where-Object {$_.RecipientType -ne "MailUser"}

For a user we need to have:

  • Name
  • Alias
  • displayName
  • exchangeGuid
  • archiveGUID
  • legacyExchangeDN
  • PrimarySMTPAddress
  • Original X500 Addresses
$ExportMembers = @()
ForEach ($Member in $Members) {
    $info = $null

    try {
        $info = Get-Mailbox $Member
    }
    catch {
        Write-Output "ERROR: $Member does not exists or has no mailbox"
    }

    if ($Info -ne $null) {
        $Object = [PSCustomObject]@{
            Name               = $info.Name
            Alias              = $info.Alias
            DisplayName        = $info.DisplayName
            ExchangeGuid       = $info.ExchangeGuid
            ArchiveGuid        = $info.ArchiveGuid
            legacyExchangeDN   = $info.legacyExchangeDN 
            PrimarySMTPAddress = $info.PrimarySMTPAddress
            X500               = $($Info.EmailAddresses) | Where-Object { $_ -like "X500:*" }
            CustomAttribute1   = "CROSSTENANT"
        }
        $ExportMembers += $object
    }
}

At this point we have all the information we needed from the Source tenant and users to create them in the new tenant.

#connect to the target tenant
Connect-ExchangeOnline

ForEach ($Mailuser in $ExportMembers) {
    $password = Get-RandomCharacters -length 9 -characters 'abcdefghiklmnoprstuvwxyz'
    $password += Get-RandomCharacters -length 1 -characters 'ABCDEFGHKLMNOPRSTUVWXYZ'
    $password += Get-RandomCharacters -length 2 -characters '1234567890'
    $password += Get-RandomCharacters -Length 2 -characters '!@#$'
    $password = Scramble-String $password

    $targetTenant = (Get-OrganizationConfig).OrganizationalUnitRoot
    $id = $mailuser.Alias + "@" + $targetTenant

    $create = $null
    Try {
        $Create = New-MailUser -Alias $Mailuser.Alias -Name $mailuser.DisplayName -DisplayName $mailuser.DisplayName -ExternalEmailAddress $Mailuser.PrimarySMTPAddress -PrimarySMTPAddress $Id -MicrosoftOnlineServicesID $id -Password (ConvertTo-SecureString $password -AsPlainText -Force) -ErrorAction SilentlyContinue
    }
    Catch {

    }
    If ($Create -ne $null) {
        Write-Output "INFO: Mailuser for $($Mailuser.Displayname) is created"
        do {
            $User = Get-MailUser $mailuser.PrimarySMTPAddress
            Write-Output "INFO: Waiting for Mailuser $($Mailuser.DisplayName) is provisioned"
            Start-Sleep -seconds 2
        } while (
            $User -eq $null
            
        )
    
        $X500 = "X500:" + $mailuser.legacyExchangeDN
    
        Try {
            Set-Mailuser -identity $User.identity -EmailAddresses @{add = $x500 }  
        }
        Catch {
            #do Nothing
        }
    
        do {
            $Control = (Get-MailUser $mailuser.PrimarySMTPAddress).EmailAddresses | Where-Object { $_ -contains $X500 }
            Write-Output "INFO: Waiting for Mailuser $($Mailuser.DisplayName) has X500 for LegacyExchangeDN added"
            Start-Sleep -seconds 2
        } while (
            $Control -eq $null
            
        )
        if ($Mailuser.X500 -eq $null) {
            #skip
        }
        else {
            Try {
                Set-Mailuser -identity $User.identity -EmailAddresses @{add = $Mailuser.X500 } 
            }
            Catch {
                #do Nothing
            }
    
            do {
                $Control = (Get-MailUser $mailuser.PrimarySMTPAddress).EmailAddresses | Where-Object { $_ -contains $mailuser.X500 }
                Write-Output "INFO: Waiting for Mailuser $($Mailuser.DisplayName) has Old X500 added"
                Start-Sleep -seconds 2
            } while (
                $Control -eq $null
            
            )
        }
        Try {
            Set-Mailuser -identity $User.identity -ExchangeGUID $MailUser.ExchangeGuid 
        }
        Catch {
            #do Nothing
        }
    
        do {
            $GUID = (Get-Mailuser -Identity $user.identity).ExchangeGUID
            start-sleep -seconds 2
        } while (
            $guid -ne $Mailuser.ExchangeGuid
        )
        Try {
            Set-Mailuser -identity $User.identity -CustomAttribute1 $MailUser.CustomAttribute1 -CustomAttribute2 $MailUser.PrimarySMTPAddress
        }
        Catch {
            #do Nothing
        }
    
        do {
            $GUID = (Get-Mailuser -Identity $user.identity).CustomAttribute1
            start-sleep -seconds 2
        } while (
            $guid -ne $Mailuser.CustomAttribute1
        )
       
    }
    else {
        $NotCreated = $Error | Select -first 1
        if ($($NotCreated.Exception.Message) -like "*Please choose another proxy address.") {
            Write-Output "ERROR: Mailuser for $($Mailuser.Displayname) is NOT created because there was an error"
            Write-Output "ERROR: User allready exists. Skipping ..."
        }
        else {
            Write-Output "ERROR: $($NotCreated.Exception.Message)"
        }
    }
}

All users in the group from the GetToTheCloudSource.onmicrosoft.com tenant are now created with the information that is needed in the GetToTheCloudTarget tenant.

The new users have in CustomAttribute2 the original SOURCE PrimarySMTPAddress and in CustomAttribute1 a placeholder to user in filter for the next post.

Share and Enjoy !

Shares
Designer (23)

Stay close to the action—follow GetToThe.Cloud across social!
Deep dives and hands‑on how‑tos on Azure Local, hybrid cloud, automation, PowerShell/Bicep, AVD + FSLogix, image pipelines, monitoring, networking, and resilient design when the internet/Azure is down.

🔗 Our channels
▶️ YouTube: https://www.youtube.com/channel/UCa33PgGdXt-Dr4w3Ub9hrdQ
💼 LinkedIn Group: https://www.linkedin.com/groups/9181126/
✖️ X (Twitter): https://x.com/Gettothecloud
🎵 TikTok: https://www.tiktok.com/@gettothecloud
🐙 GitHub: https://github.com/GetToThe-Cloud/Website
💬 Slack: DM us for an invite
📲 WhatsApp: DM for the community link

WP Twitter Auto Publish Powered By : XYZScripts.com
We use cookies to personalise content and ads, to provide social media features and to analyse our traffic. We also share information about your use of our site with our social media, advertising and analytics partners. View more
Cookies settings
Accept
Privacy & Cookie policy
Privacy & Cookies policy
Cookie name Active

Who we are

Our website address is: https://www.gettothe.cloud

Comments

When visitors leave comments on the site we collect the data shown in the comments form, and also the visitor’s IP address and browser user agent string to help spam detection. An anonymized string created from your email address (also called a hash) may be provided to the Gravatar service to see if you are using it. The Gravatar service privacy policy is available here: https://automattic.com/privacy/. After approval of your comment, your profile picture is visible to the public in the context of your comment.

Media

If you upload images to the website, you should avoid uploading images with embedded location data (EXIF GPS) included. Visitors to the website can download and extract any location data from images on the website.

Cookies

If you leave a comment on our site you may opt-in to saving your name, email address and website in cookies. These are for your convenience so that you do not have to fill in your details again when you leave another comment. These cookies will last for one year. If you visit our login page, we will set a temporary cookie to determine if your browser accepts cookies. This cookie contains no personal data and is discarded when you close your browser. When you log in, we will also set up several cookies to save your login information and your screen display choices. Login cookies last for two days, and screen options cookies last for a year. If you select "Remember Me", your login will persist for two weeks. If you log out of your account, the login cookies will be removed. If you edit or publish an article, an additional cookie will be saved in your browser. This cookie includes no personal data and simply indicates the post ID of the article you just edited. It expires after 1 day.

Embedded content from other websites

Articles on this site may include embedded content (e.g. videos, images, articles, etc.). Embedded content from other websites behaves in the exact same way as if the visitor has visited the other website. These websites may collect data about you, use cookies, embed additional third-party tracking, and monitor your interaction with that embedded content, including tracking your interaction with the embedded content if you have an account and are logged in to that website.

Who we share your data with

If you request a password reset, your IP address will be included in the reset email.

How long we retain your data

If you leave a comment, the comment and its metadata are retained indefinitely. This is so we can recognize and approve any follow-up comments automatically instead of holding them in a moderation queue. For users that register on our website (if any), we also store the personal information they provide in their user profile. All users can see, edit, or delete their personal information at any time (except they cannot change their username). Website administrators can also see and edit that information.

What rights you have over your data

If you have an account on this site, or have left comments, you can request to receive an exported file of the personal data we hold about you, including any data you have provided to us. You can also request that we erase any personal data we hold about you. This does not include any data we are obliged to keep for administrative, legal, or security purposes.

Where we send your data

Visitor comments may be checked through an automated spam detection service.
Save settings
Cookies settings