Migrate Office 365 Relying Party Trust to Different ADFS Farm

To migrate Office 365 Relying Party Trust from an existing ADFS Farm to new ADFS Farm, follow the step by step guide. Migrating Office 365 Relying Party Trust will incur a minor disruption to SSO environment.


  • Existing ADFS Farm with FQDN sts.domain.com
  • New ADFS Farm with FQDN sts1.domain.com
  • Existing Certificate CN=sts.domain.com or a wildcard certificate
  • New certificate with CN=sts1.domain.com
  • New public IP address for the public CNAME sts1.domain.com
  • A public CNAME record sts1.domain.com
  • An internal CNAME record sts1.domain.com

Note: keep the existing AAD Connect unless you have a requirement to build a new one.

Here are the steps:

Step1: Verify AAD Connect Configuration

  • Open AAD Connect, View Sign-in Option.
  • Check AAD Connect Wizard to make sure you did not configure “Federation with ADFS” Sign-in option. If you have done so then run AAD Connect Wizard again and replace the certificate and ADFS farm details to new ADFS server sts1.domain.com

Step2: Build ADFS and WAP Servers

Build a new ADFS farm side by side with an existing ADFS farm. It would be redundant effort to write another blog. Please follow my previous blog to deploy ADFS and WAP.

Building Multiple ADFS Farms in a Single Forest

Deploy Web Application Proxy Role in Windows Server 2012 R2 –Part I

Branding and Customizing the ADFS Sign-in Pages

Step3: Test SSO

Log on to the https://sts.domain.com/adfs/ls/idpinitiatedsignon.aspx using on-premises credentials to make sure you can single sign-on.

Step4: Gather list of existing federated domains from existing ADFS Farm

Log on to the existing primary ADFS Server, Open PowerShell as an Administrator, execute the following cmdlets.


Connect-MsolService –Credential $cred


Record a list of Federated Domains.

Step5: Update Office 365 RP within the new ADFS Farm

Log on to the new primary ADFS Server, Open PowerShell as an Administrator, execute the following cmdlets.


Connect-MsolService –Credential $cred

Update-MsolFederatedDomain –DomaiName “Domain.com” –SupportMultipleDomain –Confirm  Execute Update-MsolFederatedDomain Cmdlets if you have additional federated domains such as DomainB.com


Open ADFS Management Console, Make sure Office 365 RP has been created with necessary tokens and permissions. If necessary, clone all incoming and outgoing claims and permission from previous ADFS farm to new ADFS Farm and apply to the newly created Office 365 RP.

Step6: Test SSOOnce you have completed the Step5, wait for Microsoft to update their backend Identity and Federation systems. In my previous implementation work, it took 30 minutes the change to take effect.  Sign on to portal.office.com; you will be redirected to https://sts1.domain.com to authenticate. Once you have sign-in successfully, you have completed the migration work.

Step7: New AAD Connect Server (Optional)Check step1 before running AAD Connect Wizard and reconfigure sign-in options. If you need to change sign-in options, please follow the guide to change Sign-in Option.

Relevant Articles:

Upgrading AD FS to Windows Server 2016 FBL

Deploy Web Application Proxy Role in Windows Server 2012 R2 –Part II

On-prem to Office 365 Migration: PowerShell Script Collection

Connect to Azure Active Directory PowerShell without Password Prompt

#Use Case: Log on to Office 365 tenant without typing credentials.


$Password=ConvertTo-SecureString -String “MyPassword” -AsPlainText -Force

$O365CREDS= New-Object –TypeName “System.Management.Automation.PSCredential” –ArgumentList $User, $Password

#$O365CREDS = Get-Credential -Username Raihan@tenant.OnMicrosoft.Com

$SESSION = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell -Credential $O365CREDS -Authentication Basic -AllowRedirection

Import-PSSession $SESSION

Connect-MsolService -Credential $O365CREDS

Create New UPN Suffix

#Use Case: Create New UPN Suffix in Active Directory to match email domain.

Get-ADForest | Set-ADForest -UPNSuffixes @{add=”domain.com.au”}

 Changing  UPN Suffix from CSV Input

Credit: https://gallery.technet.microsoft.com/Change-UPN-592177ea

#Use Case: Changing .local domain to email domain before the Office 365 migration.

#CSV header of input file is Loginid and each row containing one samaccountname.

 $oldSuffix = ‘existingupn.com’

$newSuffix = ‘newupn.com’

Import-CSV userlist.csv | ForEach-Object {

$usr = get-aduser $_.loginid |Select userprincipalname, samaccountname

$newUpn = $usr.UserPrincipalName.Replace($oldSuffix,$newSuffix)

Set-ADUser -identity $usr.samaccountname -UserPrincipalName $newUpn -Verbose


 Changing UPN Suffix to Match Email Address

#Use Case: To match UPN suffix with primary email address on the general properties of Active Directory users.

Step 1: Export all UserPrincipalNames and Email Addresses from the AD to a CSV File.

Get-AdUser -Filter * -Properties UserPrincipalName, Name, EmailAddress | Select-Object UserPrincipalName, Name, EmailAddress | Export-CSV -Path C:\MyADUsers.csv -NoTypeInformation

Step 2: Use that CSV file to bulk change the UserPrincipalNames to match those Email Addresses.

CSV Headers are UserPrincipalName and EmailAddress

#Script to Change the UPN on the Active Directory#

#This script should run from an Active Directory Module for Windows PowerShell#

$UserCount = 0

Import-Csv -Path C:\MyADUsers.csv | ForEach-Object {

$UPN = $_.UserPrincipalName

Write-Host “Working on user:” $UPN

Get-ADUser -Filter {UserPrincipalName -Eq $UPN} | Set-AdUser -userprincipalname $_.EmailAddress

$usercount = $usercount +1


Write-Host “Number of users on your CSV: $UserCount”

Write-Host “UPN’s Changed”

 Changing UPN to Match SMTP

  #Use Case: Select all users in a domain and assign new UPN in bulk

Get-ADUser -Filter {mail -like “*@domain.com.au”} -Properties Mail | Foreach { Set-ADUser $_ -UserPrincipalName $_.mail }

Above command will copy primary SMTP of each user and make that SMTP to match UPN suffix. To complete this task, you must pre-populate primary SMTP before you run this command.

 Changing UserName to FirstName.LastName

#Use Case: If you have a scenario where username is firstname@domain.com.au but your username should match the SMTP which is firstname.lastname@domain.com.au . In this scenario you can extract all username from Active Directory, create a CSV or txt file with one column with just username and no @domain.com.au then the below script will modify username from FirstName to FirstName.LastName@domain.com.au

Get-Content .\users.csv | foreach { .\Update-Username.ps1 –Username $_ –UPNSuffix domain.com.au -LogFile .\changes.txt -WhatIf }

Credit: https://gallery.technet.microsoft.com/Updating-AD-Usernames-to-20bd329b

Add Alias and Set as Primary SMTP

Credit: https://social.technet.microsoft.com/Forums/exchange/en-US/f1dd3112-13bc-49e6-a5a2-a4b061ce5e9c/powershell-script-to-add-new-smtp-address-as-primary-address

#Use case: You have synchronized all users from on-prem Active Directory to Azure Active Directory but users email address is showing default domain e.g. @tenant.onmicrosoft.com. Now you want to add a alias and set that alias as primary SMTP to match email domain. 

 Import-Csv c:\data.csv | Foreach{

$maileg = Get-Mailbox -Identity $_.Name

$maileg.EmailAddresses += $_.emailaddress

$maileg | Set-Mailbox -EmailAddresses $maileg.EmailAddresses -PrimarySmtpAddress $_.emailaddress


 Assign Office 365 licenses from CSV File Input

#Use Case: Assign licenses in bulk. 

Step1: Find Current Sku

Get-MsolAccountSkuId to find out current Sku

Step2: Create a CSV file with UserPrincipalName as header e.g. firstname.lastname@domain.com.au

Step3: Run the command.

$path= Import-Csv -Path “C:\CSV\E1Licenses.csv”

foreach ($item in $path){

$MSOLUserName= $item.UserPrincipalName

$AccountSkuId = “tenant:STANDARDPACK”

$UsageLocation = “AU”

$LicenseOptions = New-MsolLicenseOptions -AccountSkuId $AccountSkuId

Set-MsolUser -UserPrincipalName $MSOLUserName -UsageLocation $UsageLocation

Set-MsolUserLicense -UserPrincipalName $MSOLUserName -AddLicenses $AccountSkuId  -LicenseOptions $LicenseOptions



  • For E1 license is StandardPack and for E3 license is EnterprisePack
  • For Country Code, use ISO 3166 two-letter country-code standard e.g. Australia is AU

 Reclaim Office 365 Licenses

Step1: Export Last Logon to Office 365 in a SSO environment

Follow the URL https://gallery.technet.microsoft.com/office/Export-Office-365-User-7fc0b73f to Extract last log on report to make sure user did not log on recently and active.

Step2: Create a CSV file with a header UserPrincipalName

Step3: Remove Office 365 Licenses from CSV File Input

$path= Import-Csv -Path “C:\CSV\E1NA.csv”

foreach ($item in $path){

$MSOLUserName= $item.UserPrincipalName

$AccountSkuId = “Tenant:ENTERPRISEPACK”

Set-MsolUserLicense -UserPrincipalName $MSOLUserName -RemoveLicenses $AccountSkuId


 Import Contact from On-prem to Office 365 via CSV File

#Use Case: This script is to import all the contact from on-premises Exchange to Office 365 from a CSV input.

Step1: Run Export all mail contact Get-MailContact | Export-Csv c:\CSV\MailContact.CSV 

Step2: Create a CSV file with CSV headers are Name,DisplayName,ExternalEmailAddress,FirstName,LastName

 Step3: Import Mail Contact  

Import-Csv | ForEach {New-MailContact -Name $_.Name -DisplayName $_.Name -ExternalEmailAddress $_.ExternalEmailAddress -FirstName $_.FirstName -LastName $_.LastName}

 Import Room Mailboxes from On-prem to Office 365 via CSV input

 Step1: Export Room Mailboxes  Get-Mailbox -RecipientTypeDetails RoomMailbox | Export-Csv c:\CSv\RoomMailboxes.csv Get-Mailbox -RecipientTypeDetails EquipmentMailbox | Export-Csv c:\CSv\EquipmentMailboxes.csv

 Step2: Create CSV file with header Name,Alias,PrimarySMTPAddress

Step3: Run the following command to import Room Mailbox

Import-Csv “C:\Scripts\RoomMailboxes.csv” | foreach-object { New-Mailbox -Name $_.Name -Alias $_.Alias -PrimarySmtpAddress $_.Address -Room }

 Assign Shared Mailboxes Permission to Match on-prem Shared Mailboxes

Step1: Export Shared Mailbox Full Access Permision

Get-Mailbox -RecipientTypeDetails SharedMailbox | Get-MailboxPermission | where { ($_.AccessRights -eq “FullAccess”) -and ($_.IsInherited -eq $false) -and -not ($_.User -like “NT AUTHORITY\SELF”) }

Step2: Export Shared Mailbox SendAs Permision

Get-Mailbox -RecipientTypeDetails SharedMailbox | Get-ADPermission | Where {$_.ExtendedRights -like “Send-As” -and $_.User -notlike “NT AUTHORIT\SELF” -and $_.Deny -eq $false} | ft Identity,User,IsInherited -AutoSize

Step3: Prepare two CSV file with header like Name,User where name is the username and user primary SMTP of shared Mailbox.

Step4: Assign SendAs Permission to Shared Mailboxes

$Mailboxes = import-csv C:\CSV\Mailboxes1.csv

Foreach ($Mailbox in $Mailboxes) {Add-RecipientPermission -Identity $Mailbox.Name -Trustee $Mailbox.User -AccessRights “SendAs”}

Step5: Assign Full Access Permission to Shared Mailboxes

$Mailboxes = import-csv C:\CSV\Mailboxes1.csv

Foreach ($Mailbox in $Mailboxes) {Add-MailboxPermission -Identity $Mailbox.Name -user $Mailbox.User -AccessRights ‘FullAccess’ -InheritanceType All}

 Import DL from on-prem to office 365 including Memberships

Download and install PowerShell module from this URL


Step1: Extract list of AD Groups

Get-ADGroupMember -Id “Group Name” | Export-CSV c:\temp\GroupOutput.CSV –NoTypeInformation

Step2: Extract AD Group’s memberships

$groups = Get-Content c:\temp\ADGroupsAdmin.csv           

foreach($Group in $Groups) {                    

Get-ADGroupMember -Id $Group | select  @{Expression={$Group};Label=”Group Name”},* | Export-CSV c:\temp\GroupsInfo.CSV -NoTypeInformation -Append           


Step3: Export ManagedBy Properties of DL

$DL = ‘OU=example,DC=Domain,DC=com’

$DL | ForEach {Get-ADGroup -Filter * -Properties ManagedBy -SearchBase $_ } |

 Select Name, ManagedBy | Sort -Property Name | Out-File C:\ManagedBy.csv

Step4: Create Distribution Group in Bulk

CSV Headers are Name,DisplayName,Alias,Address,Type

Import-CSV “C:\CSG\distributiongroup.csv” | foreach {New-DistributionGroup -Name $_.name -DisplayName $_.DisplayName -Alias $_.Alias -PrimarySmtpAddress $_.Address -Type $_.Type}

Step5: Add Members to Distribution Group in Bulk

CSV headers are Indentity,Members

Import-Csv “C:\CSG\addmem1.csv” | foreach{Add-DistributionGroupMember -Identity $_.identity -Member $_.members}

Step6: Add ManagedBy properties of Distribution Groups

CSV Headers are GroupName,ManagedBy,User

$list=import-csv C:\AddDistributionGroupOwnerList.csv

Foreach ($i in $list) {

 $grp=get-distributiongroup $i.groupname


 $newuser=get-user $i.user


 Set-distributiongroup $grp -managedby $newmanage -bypasssecuritygroupmanagercheck


 Enable remote Mailboxes in Bulk

This script is useful in hybrid environment when you don’t want to create a mailbox on the on-prem server and then migrate to Office 365. Instead you enable remote mailbox and assign Office 365 licenses to user and create the mailboxes in the Office 365 tenant.  

$Users = Import-csv C:\CSv\EnableRemoteMailbox.csv$Users | ForEach-Object {Enable-RemoteMailbox -identity $_.userprincipalname -RemoteRoutingAddress ($_.samaccountname+’@TENANT.mail.onmicrosoft.com’)} 

Add Proxy Address to the On-prem Mailboxes

This script is very handy if you would like to add alias to all mailboxes in bulk. Alias or proxy address can be used for various reason including mailflow co-existence between disparate mail systems to Office 365 @tenant.mail.onmicrosoft.com address during IMAP migration.

CSV Headers are Name,ProxyAddresses

 Import-Csv C:\AddressList.csv | ForEach-Object {

  $name = $_.Name

  $proxy = $_.ProxyAddresses -split ‘;’

  Set-Mailbox -Identity $name -EmailAddresses @{add= $proxy}


 Setup Forwarding Address on the On-prem Server

This script is to create forwarding address or target address in bulk. Target address is used to configure mailflow co-existence between disparate mail systems to Office 365 @tenant.mail.onmicrosoft.com address during IMAP migration.

CSV Headers are Mailbox,ForwardTo

Import-CSV “C:\CSV\Users.csv” | ForEach {Set-Mailbox -Identity $_.mailbox -ForwardingAddress $_.forwardto}

Terms & Conditions:

Before you run any script from any internet source, make sure you understand the risks associated with the script. Understand what has been written on the script, test and validate the script then you run the script. These script does not come with at-fault warranty. These scripts come with As is. Use one or all the scripts when necessary and if the my scenario matches yours. Good luck!