Bulk Remove Domain from users in 365 ( UPN and SMTP )

Remove Domain from UPN

Connect-MsolService
$domain = "domain.com"
$TenantDomain = @((Get-MsolDomain |?{$_.Name -match '.onmicrosoft.com' -and $_.Name -notmatch '.mail.'}).Name)?
$msolUsersWithDomain = @(Get-MsolUser -All | ? {$_.UserPrincipalName -match $domain})?
#Remove UPN
$msolUsersWithDomain | % {Set-MsolUserPrincipalName -ObjectId $_.objectId -NewUserPrincipalName ($_.UserPrincipalName.Split("@")[0]+ "@" +$TenantDomain );}

Remove SMTP address

Connect-ExchangeOnline
$domain = "domain.com"
$MailboxeswithDomain = @(Get-Recipient -ResultSize Unlimited | where {$_.PrimarySmtpAddress -match "$Domain" -or $_.EmailAddresses -match "$Domain"} | select PrimarySmtpAddress,EmailAddresses,RecipientType,RecipientTypedetails | Sort-Object -Property RecipientType,RecipientTypedetails)?

foreach ($Mailbox in $MailboxeswithDomain) {  
    $Mailbox.EmailAddresses | Where-Object { ($_ -clike "smtp*") -and ($_ -like "*@$domain") } | 

    # Perform operation on each item
    ForEach-Object {

        # Remove the -WhatIf parameter after you tested and are sure to remove the secondary email addresses
        Set-Mailbox $Mailbox.DistinguishedName -EmailAddresses @{remove = $_ } -WhatIf

        # Write output
        Write-Host "Removing $_ from $Mailbox Mailbox" -ForegroundColor Green
    }
}


1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...