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!

About Raihan Al-Beruni

My Name is Raihan Al-Beruni. I am working as an Infrastructure Architect in Data Center Technologies in Perth, Western Australia. I have been working on Microsoft technologies for more than 15 years. Other than Microsoft technologies I also work on Citrix validated solution and VMware data center virtualization technologies. I have a Masters degree in E-Commerce. I am certified in Microsoft, VMware, ITIL and EMC. My core focus is on cloud technologies. In my blog I share my knowledge and experience to enrich information technology community as a whole. I hope my contribution through this blog will help someone who wants more information on data center technologies.
Gallery | This entry was posted in Exchange Server and tagged , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s