How to remove a custom domain from Office 365

Introduction

This script will remove a custom domain from Office 365.

Scenarios

This script will remove a custom domain from Office 365 when there is an error message "Remove-MsolDomain : Unable to remove this domain. Use Get-MsolUser -DomainName<domain name> to retrieve a list of objects that are blocking removal."

Prerequisites
This script requires Windows Azure Active Directory Module for Windows PowerShell. Please download and install the package. This script cannot work correctly without this package.

Script

You can use this script in the following way.

1. Open Windows PowerShell.

2. Type the one command< Script Path> at the Windows PowerShell Console.
For example, type C:\Script\
RemoveDomainO365.ps1

Here are some code snippets for your reference.

PowerShell
Edit|Remove
foreach($User in $UserList)  
{  
    $UserName = $reg.Match($User.UserPrincipalName).Value  
    $NewName = $UserName + "@" + $Tenantdomain  
    $Existed = $null  
    $Existed = Get-MsolUser -UserPrincipalName $NewName  
    $i = 1  
    while($Existed -ne $null)  
    {  
        $Existed = $null  
        $UserName = $reg.Match($User.UserPrincipalName).Value  
        $Username = $UserName + "." + $i  
        $NewName = $UserName + "@" + $Tenantdomain  
        $Existed = Get-MsolUser -UserPrincipalName $NewName  
    }  
    Set-MsolUserPrincipalName -UserPrincipalName $User.UserPrincipalName -NewUserPrincipalName $NewName  
}
 

Examples

Example: remove domain contoso.com from Office 365  

The sample is shown below
RemoveDomainO365.ps1 -Credential $Credential –Domain "Contoso.com"
 

Reference
http://support.microsoft.com/kb/2787210/en-us

 

Microsoft All-In-One Script Framework is an automation script sample library for IT Professionals. The key value that All-In-One Script Framework is trying to deliver is Scenario-Focused Script Samples driven by IT Pros' real-world pains and needs. The team is monitoring all TechNet forums, IT Pros' support calls to Microsoft, and script requests submitted to TechNet Script Repository. We collect frequently asked IT scenarios, and create script samples to automate the tasks and save some time for IT Pros. The team of All-In-One Script Framework sincerely hope that these customer-driven automation script samples can help our IT community in this script-centric move.