Fix Orphaned Groups in EntraID that do not exist in Active Directory

In this quick blog post, I'll address an issue I encountered recently. I had a request to delete an Exchange distribution group, but the challenge was that the group was not in Active Directory (AD) but in EntraID. After some investigation, I discovered it was orphaned, meaning it existed in EntraID but not in AD. To remove it, I had to use PowerShell.

Identifying and Removing Orphaned Groups

After locating the orphaned group, I wondered how many other groups were in a similar state. To address this, I decided to write a PowerShell script to find and delete these groups.

Script Overview

Step 1: Install the Microsoft Graph PowerShell Module

First, you'll need to install the Microsoft Graph PowerShell Module. Use the following command to install it:

Install-Module Microsoft.Graph -Scope AllUsers

Step 2: Connect to Microsoft Graph with Group Read Rights

Next, connect to Microsoft Graph to retrieve the groups that are synced from on-premises to Azure:

Connect-MgGraph -Scopes 'Group.Read.All'
$props = "id","OnPremisesSamAccountName","OnPremisesSyncEnabled"
$Azure = Get-MgGroup -All -Property $props | select OnPremisesSamAccountName, OnPremisesSyncEnabled

Step 3: Retrieve Groups from Active Directory

You'll also need the Active Directory PowerShell module. Although I won't cover how to load it here, the next command retrieves all groups from Active Directory:

$AD = get-adgroup -filter * 

Step 4: Filter and Compare Groups

To compare groups, filter the outputs. Adjust the AD part of the command to use SamAccountName since the DisplayName may be blank for some universal AD groups. This will compare the Azure AD group DisplayName with the Active Directory SamAccountName:

$AZDN=$Azure.displayname
$ADDN=$AD.SamAccountName


$Groups = $AZDN  | where-object {$ADDN -NotContains $_}

Step 5: Obtain EntraID Values

Get the EntraID "ID" values, which are numeric, for the groups not found in Active Directory:

$objectid = foreach ($id in $Groups) {
    Get-MgGroup -filter "DisplayName eq '$id'"
}
$objectid2 = $objectid.Id

Step 6: Connect to EntraID

Connect to EntraID:

Connect-AzureAD

Step 7: Remove the Groups

Finally, remove the groups from EntraID. Double-check your work as AD Connect should repopulate the groups if you make a mistake:

foreach ($id2 in $objectid2) {
    Remove-AzureADGroup -ObjectId "$id2"
}

Conclusion

That's the script. Hopefully, it helps if you ever encounter this situation. Always validate your outputs to ensure that the groups do not exist in Active Directory before removal. You can also download the script from my Github page, located here.

TBJ Consulting

TBJ Consulting