M365 Email AddressRemoval

Removing a Email Address from Office 365 using PowerShell involves several steps. Change Email Addresses for all Microsoft 365 Mailboxes and Groups

Prerequisites

  • M365 Admin Access: You need to have the necessary admin permissions

  • Powershell : Install the Microsoft Azure Active Directory Module and Exchange Online Management Module for Windows PowerShell

Important Notes

  • Always ensure you have backups or have planned for any required changes before removing a domain.

  • Before running this script in a production environment, test it in a safe, non-production environment to avoid accidental data loss or service disruption.

# Output will be added to C:\temp folder

Start-Transcript -Path "C:\tempRemove-AliasDomain.log" -Append

# Define the domain to remove

$domainToRemove = "joseph.com"

#Connect to MsolService

Import-Module MsOnline

$credential = get-credential

Connect-MsolService -Credential $credential

#Connect to Exchange Online:

$ExchangeSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri “https://outlook.office365.com/powershell-liveid/” -Credential $credential -Authentication “Basic” –AllowRedirection

Import-PSSession $ExchangeSession

# Remove domain email addresses from user mailboxes

$mailboxes = Get-Mailbox -ResultSize Unlimited

foreach ($mailbox in $mailboxes) {

$updated = $false

$newAddresses = @()

foreach ($address in $mailbox.EmailAddresses) {

if ($address -like "*@$domainToRemove") {

Write-Output "Removing $address from mailbox $($mailbox.PrimarySmtpAddress)"

$updated = $true

} else {

$newAddresses += $address

}

}

if ($updated) {

Set-Mailbox -Identity $mailbox.Identity -EmailAddresses $newAddresses

}

}

# Remove domain email addresses from shared mailboxes

$sharedMailboxes = Get-Mailbox -ResultSize Unlimited -RecipientTypeDetails SharedMailbox

foreach ($mailbox in $sharedMailboxes) {

$updated = $false

$newAddresses = @()

foreach ($address in $mailbox.EmailAddresses) {

if ($address -like "*@$domainToRemove") {

Write-Output "Removing $address from shared mailbox $($mailbox.PrimarySmtpAddress)"

$updated = $true

} else {

$newAddresses += $address

}

}

if ($updated) {

Set-Mailbox -Identity $mailbox.Identity -EmailAddresses $newAddresses

}

}

# Remove domain email addresses from distribution groups

$distributionGroups = Get-DistributionGroup -ResultSize Unlimited

foreach ($group in $distributionGroups) {

$updated = $false

$newAddresses = @()

foreach ($address in $group.EmailAddresses) {

if ($address -like "*@$domainToRemove") {

Write-Output "Removing $address from distribution group $($group.PrimarySmtpAddress)"

$updated = $true

} else {

$newAddresses += $address

}

}

if ($updated) {

Set-DistributionGroup -Identity $group.Identity -EmailAddresses $newAddresses

}

}

Write-Output "Domain email addresses removal process completed."

Stop-Transcript