Detecting Orphaned Users in Azure/Entra ID AD Connect Sync with PowerShell


Executive Summary

Over time, Azure/Entra ID AD Connect Sync has undergone changes, and if you've been using it or inheriting it, you might encounter orphaned users. Identifying these users, especially amidst the vast user base of Entra ID, can be daunting. To address this challenge, I've developed a PowerShell script capable of detecting orphaned users.

The Script

To execute this script, you'll need to interact with the MS Graph and install the Microsoft Graph PowerShell Module. Additionally, you must create an Azure Application for accessing the Microsoft Graph, a process detailed in this blog post.

Connecting to MS Graph

Install-Module -Name MSAL.PS
#Provide your Office 365 Tenant Domain Name or Tenant Id
$TenantId = "XXXXXX"
# Your AppClientID
$AppClientId="XXXXXXXX"
$MsalParams = @{
    ClientId = $AppClientId
    TenantId = $TenantId
    Scopes = "https://graph.microsoft.com/User.Read.All","https://graph.microsoft.com/AuditLog.Read.All"
}
$MsalResponse = Get-MsalToken @MsalParams
$AccessToken = $MsalResponse.AccessToken


Connecting to Active Directory and EntraID

To access the Active Directory, ensure you have the Active Directory PowerShell module loaded by executing import-module ActiveDirectory. Then, query both directories and store the results in arrays.

#Get EntraID users that are Syncing from OnPrem
$EntraID = Get-MgUser -All -Filter "OnPremisesSyncEnabled eq true"
#Get all Active Directory Users
$AD = get-aduser -filter * -Properties *
#Filter Output to an Array that only Contains UserPrincipalName
$EntraIDUPN=$EntraID.UserPrincipalName
$ADUPN=$AD.UserPrincipalName

Utilize a For-Each Loop to compare the results and output orphaned users to the command line.

#Perform a For-Each Object Loop to find the Users who are Orphaned in EntraAD and Write it out to the Command Line
$EntraIDUPN | ForEach-Object {
    if ($ADUPN -notcontains $_) {
        Write-Host $_
    }
}

Final Thoughts

This script aims to assist in identifying orphaned users within EntraID. I'm sharing it on my blog as I couldn't find similar examples online, and I hope it benefits others. Developing this script took longer than anticipated but I'm satisfied with the outcome. I am also pleased with my growth in PowerShell scripting proficiency. You can also find this script on my GitHub site.

TBJ Consulting

TBJ Consulting