Office 365: Bulk Remove Domains from Tenant

Modified on Tue, 21 Apr at 6:45 PM

Get list of domains

Check the MX for each one in DNS

If it's not pointing to Office 365 (i.e. the domain has expired) then try to remove it


Connect-ExchangeOnline
Connect-MgGraph -Scopes "Domain.ReadWrite.All"

# 1. Fetch all accepted domains from the tenant
$AcceptedDomains = Get-AcceptedDomain | Select-Object -ExpandProperty DomainName

Write-Host "Found $($AcceptedDomains.Count) domains. Starting DNS checks..." -ForegroundColor Cyan

# 2. Iterate and check MX records
$NonO365Domains = foreach ($Domain in $AcceptedDomains) {
  # Query for MX records (using -ErrorAction SilentlyContinue to handle domains with no MX)
  $MXLookup = Resolve-DnsName -Name $Domain -Type MX -ErrorAction SilentlyContinue
  
  # Extract the hostnames from the MX records
  $MXHosts = $MXLookup.NameExchange

  # Check if any record points to Microsoft 365
  # Standard format is: yourdomain-com.mail.protection.outlook.com
  $PointsToO365 = $MXHosts | Where-Object { $_ -like "*mail.protection.outlook.com" }

  if (-not $PointsToO365) {
    $Domain
  }
}

# 3. Output the results
if ($NonO365Domains) {
    Write-Host "`nDomains NOT pointing to Office 365:" -ForegroundColor Yellow
    $NonO365Domains | Format-Table -AutoSize
}
else {
    Write-Host "`nAll domains are correctly pointing to Office 365." -ForegroundColor Green
}

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article