AD Connect and hard matching on premise AD accounts with Microsoft 365 Azure and ImmutableId

Issue
I need to re-sync my on premise users with Office 365 having migrated from an old domain to a new.
N.B – This will only work on “Cloud” users, if your users are still AD Synced you will not be able to set the ImmutableID
Solution
In order to re-sync the users back to Office 365 you need to ensure that the following attributes are identical on prem and in cloud.
- userPrincipalName (REQUIRED)
- ImmutableId (REQUIRED)
- EMail (REQUIRED)
- Display Name (OPTIONAL)
The process has two steps, get the current ImmutableId on the on prem user and then set it on the cloud 365 user so when you re-run the sync the users will hard match. Below are various methos to get the ImmutableId for a single user or all users in an OU.
If you are doing a bulk update I would use the Get all users in an OUs UserPrincipalName, objectGUID and convert to ImmutableID then export to CSV step to export to CSV, open the file in Excel and use the =concatenate function to create individual commands to update each cloud user as per Set the new ImmutableID on the cloud account
Install the prerequisites and connect to 365
Install-Module MsOnline
Connect-MsolService
At this point you will be prompted for you Office 365 global admin credentials, please enter them and click sign in.
Getting a single cloud users ImmutableId
Get-MsolUser -UserPrincipalName USER@DOMAIN.COM | select ImmutableId, UserPrincipalName
Get all cloud immuntable IDs to CSV
Get-MsolUser -All | select ImmutableId, UserPrincipalName | Export-CSV users.csv
Get a single users on premise ImmutableID(objectGuid) using ldifde
ldifde -f export.txt -r “(Userprincipalname=USER@DOMAIN.COM)” -l “objectGuid, userPrincipalName”
Get all users in an OUs UserPrincipalName, objectGUID and convert to ImmutableID then export to CSV
Get-ADUser -Filter * -SearchBase “DC=TRUST,DC=LOCAL” -Properties objectGUID | Select-Object UserPrincipalName, objectGUID, @{Name = ‘ImmutableID’; Expression = { [system.convert]::ToBase64String(([GUID]$_.objectGUID).ToByteArray()) } } | Export-CSV users.csv
Note that the objectGUID exported in PowerShell are different to the ones exported using ldifde as they have been pre converted to a Base64 string.
Set the new ImmutableID on the cloud account
Set-MsolUser -UserPrincipalName USER@DOMAIN.COM -ImmutableID “ABCdefGHIjklMNO==”
Knows Errors
Set-MsolUser : Uniqueness violation. Property: SourceAnchor
If the user account has previously existed and has been synced they could exist as a deleted user with the same ImmutableID set

This can be solved by removing the user from the deleted items with the below command
Remove-MsolUser -UserPrincipalName USER@DOMAIN.COM -RemoveFromRecycleBin