Auditing service account drift between Active Directory and Entra ID

A three-script, snapshot-based audit that finds missing, ownerless, still-enabled and over-entitled service accounts across AD and Entra ID, plus how to fix each one.

By Sherry Yuan, CISA11 min read

HR feeds keep human accounts honest: joiners get created, leavers get disabled. Service accounts have no HR record, so in a hybrid directory nobody notices when the on-premises copy and the Entra ID copy stop agreeing. An account can be disabled in Active Directory and still sign in to the cloud, or have an owner on-premises and nobody in Entra ID.

This article gives you a repeatable audit for that drift: export AD, export Entra ID, compare the two snapshots offline, and then fix each kind of finding correctly. Several fixes that look obvious don’t work on synced objects, and the pitfalls section covers those.

The scenario

You run Microsoft Entra Connect Sync. Service accounts are ordinary AD user objects in a dedicated OU (for example OU=Service Accounts,DC=contoso,DC=com), and they sync to Entra ID like any user. For an audit you need to show, at a point in time, which of those accounts have drifted. Four kinds of drift come up again and again:

  1. Missing in Entra ID: the account exists in AD but has no linked cloud object, or the only cloud object with its UPN is a cloud-only account that sync never took over.
  2. Owner gap: AD has a manager (the account owner) and Entra ID has none, or a different one.
  3. Disabled in AD, enabled in Entra ID: the most dangerous case. The account is dead on-premises but can still get cloud tokens.
  4. Group membership mismatch: membership of synced groups differs between the two sides.

Key concepts

Which objects this audit covers

This audit covers user-object service accounts, the kind Entra Connect syncs as ordinary users. Other non-human identities sit elsewhere and need their own review. For the wider taxonomy, see Four kinds of non-human identity.

Where How a service account is recognised
AD, user object Same objectClass as people. You rely on an OU or a naming convention such as svc-
AD, managed (gMSA) Its own object class, msDS-GroupManagedServiceAccount. Get-ADUser doesn’t return it
Entra ID, synced A user under /users. Recognised by the same OU, name or attribute convention
Entra ID, workload A service principal under /servicePrincipals, typed by servicePrincipalType

When a new object arrives from AD, Entra ID tries to match it to an existing cloud object:

  • Hard match: the object’s source anchor (the Base64 form of mS-DS-ConsistencyGuid or objectGUID, depending on configuration) equals the cloud user’s onPremisesImmutableId.
  • Soft match: no hard match, but userPrincipalName or the primary SMTP address matches.

After a match the object is managed on-premises. Every attribute that has a value in AD overwrites the cloud value, and Graph refuses changes to synced properties.

What happens when an object leaves sync scope

When an object is filtered out, for example by moving it to an OU that isn’t selected for sync, Entra Connect deletes the cloud object it provisioned. The user goes to the Entra ID recycle bin. Objects that Connect never provisioned are left alone. The default scheduler runs a delta cycle every 30 minutes.

Solution

The audit is three scripts, each producing a file the next one reads. Snapshots give you point-in-time evidence for the auditor. They also keep the comparison logic away from live directories, so you can rerun it as often as you like.

Part 1: export Active Directory

Run this on a domain-joined host with the RSAT ActiveDirectory module. It resolves each manager DN to a UPN and each group DN to a SID, because SIDs are what Entra ID stores as onPremisesSecurityIdentifier.

[CmdletBinding()]
param(
    [string]$SearchBase = 'OU=Service Accounts,DC=contoso,DC=com',
    [string]$OutputFile = 'C:\Temp\AuditSnapshots\AD_ServiceAccounts_Snapshot.json'
)
Import-Module ActiveDirectory
$Dir = [System.IO.Path]::GetDirectoryName($OutputFile)
if (-not (Test-Path $Dir)) { New-Item -ItemType Directory -Path $Dir -Force | Out-Null }

Write-Host 'Extracting AD service accounts...' -ForegroundColor Cyan
$ADUsers = Get-ADUser -SearchBase $SearchBase -Filter * -Properties UserPrincipalName, Enabled, Manager, MemberOf
$Snapshot = [System.Collections.Generic.List[object]]::new()

foreach ($User in $ADUsers) {
    $ManagerUPN = $null
    if ($User.Manager) {
        $MgrObj = Get-ADUser -Identity $User.Manager -Properties UserPrincipalName -ErrorAction SilentlyContinue
        $ManagerUPN = $MgrObj.UserPrincipalName
    }
    $GroupSIDs = [System.Collections.Generic.List[string]]::new()
    foreach ($GroupDN in $User.MemberOf) {
        $GrpObj = Get-ADGroup -Identity $GroupDN -ErrorAction SilentlyContinue
        if ($GrpObj) { $GroupSIDs.Add($GrpObj.SID.Value) }
    }
    $Snapshot.Add([pscustomobject]@{
        SamAccountName    = $User.SamAccountName
        UserPrincipalName = $User.UserPrincipalName
        SID               = $User.SID.Value
        Enabled           = $User.Enabled
        ManagerUPN        = $ManagerUPN
        GroupSIDs         = $GroupSIDs
    })
}
ConvertTo-Json -InputObject @($Snapshot) -Depth 5 | Out-File -FilePath $OutputFile -Encoding utf8
Write-Host "AD snapshot saved: $($Snapshot.Count) accounts" -ForegroundColor Green

Part 2: export Entra ID

This uses the Microsoft Graph PowerShell SDK. manager is a relationship, not a property, so selecting it with -Property returns nothing. The script calls Get-MgUserManager for each user, which returns 404 when no manager is set. Group memberships are reduced to the groups that carry an on-premises SID.

[CmdletBinding()]
param(
    [string]$UserOutputFile  = 'C:\Temp\AuditSnapshots\Entra_Users_Snapshot.json',
    [string]$GroupOutputFile = 'C:\Temp\AuditSnapshots\Entra_Groups_Snapshot.json'
)
Import-Module Microsoft.Graph.Users, Microsoft.Graph.Groups
if (-not (Get-MgContext)) { Connect-MgGraph -Scopes 'User.Read.All', 'Group.Read.All' -NoWelcome }

Write-Host 'Extracting Entra ID users...' -ForegroundColor Cyan
$Users = @(Get-MgUser -All -PageSize 999 -Property 'id,userPrincipalName,accountEnabled,onPremisesSecurityIdentifier,onPremisesSyncEnabled,onPremisesLastSyncDateTime')
$UserSnapshot = [System.Collections.Generic.List[object]]::new()

foreach ($u in $Users) {
    $MgrUPN = $null
    $MgrObj = Get-MgUserManager -UserId $u.Id -ErrorAction SilentlyContinue
    if ($MgrObj) { $MgrUPN = $MgrObj.AdditionalProperties['userPrincipalName'] }

    $GroupSIDs = [System.Collections.Generic.List[string]]::new()
    $MemberOf = @(Get-MgUserMemberOf -UserId $u.Id -All |
        Where-Object { $_.AdditionalProperties['@odata.type'] -eq '#microsoft.graph.group' })
    foreach ($grp in $MemberOf) {
        $sid = $grp.AdditionalProperties['onPremisesSecurityIdentifier']
        if ($sid) { $GroupSIDs.Add($sid) }
    }
    $UserSnapshot.Add([pscustomobject]@{
        Id                           = $u.Id
        UserPrincipalName            = $u.UserPrincipalName
        AccountEnabled               = $u.AccountEnabled
        OnPremisesSecurityIdentifier = $u.OnPremisesSecurityIdentifier
        OnPremisesSyncEnabled        = $u.OnPremisesSyncEnabled
        OnPremisesLastSyncDateTime   = $u.OnPremisesLastSyncDateTime
        ManagerUPN                   = $MgrUPN
        MemberOfGroupSIDs            = $GroupSIDs
    })
}
ConvertTo-Json -InputObject @($UserSnapshot) -Depth 5 | Out-File -FilePath $UserOutputFile -Encoding utf8

Write-Host 'Extracting synced Entra ID groups...' -ForegroundColor Cyan
$Groups = @(Get-MgGroup -All -PageSize 999 -Property 'id,displayName,onPremisesSecurityIdentifier,onPremisesSyncEnabled' |
    Where-Object { $_.OnPremisesSyncEnabled -and $_.OnPremisesSecurityIdentifier } |
    Select-Object Id, DisplayName, OnPremisesSecurityIdentifier)
ConvertTo-Json -InputObject $Groups | Out-File -FilePath $GroupOutputFile -Encoding utf8
Write-Host 'Entra ID snapshots saved.' -ForegroundColor Green

ConvertTo-Json -InputObject @(...) writes [] for an empty result. Piping an empty collection into ConvertTo-Json writes an empty file, and Part 3 then fails when it parses it.

Part 3: compare offline

Part 3 runs without connecting to any directory. It indexes the Entra ID users by SID and by UPN. It matches each AD account on SID first and falls back to UPN, which is how it finds cloud-only look-alikes.

[CmdletBinding()]
param(
    [string]$ADSnapshotPath     = 'C:\Temp\AuditSnapshots\AD_ServiceAccounts_Snapshot.json',
    [string]$EntraUserPath      = 'C:\Temp\AuditSnapshots\Entra_Users_Snapshot.json',
    [string]$EntraGroupPath     = 'C:\Temp\AuditSnapshots\Entra_Groups_Snapshot.json',
    [string]$FinalCSVReportPath = 'C:\Temp\AuditSnapshots\Final_Audit_DriftReport.csv'
)
$AD_SAs      = Get-Content -Raw -Path $ADSnapshotPath | ConvertFrom-Json
$Entra_Users = Get-Content -Raw -Path $EntraUserPath  | ConvertFrom-Json
$EntraGroups = Get-Content -Raw -Path $EntraGroupPath | ConvertFrom-Json

$BySid = @{}; $ByUpn = @{}
foreach ($u in $Entra_Users) {
    if ($u.OnPremisesSecurityIdentifier) { $BySid[$u.OnPremisesSecurityIdentifier] = $u }
    if ($u.UserPrincipalName) { $ByUpn[$u.UserPrincipalName.ToLower()] = $u }
}
$SyncedGroups = @{}
foreach ($g in $EntraGroups) { $SyncedGroups[$g.OnPremisesSecurityIdentifier] = $g }

$Findings = [System.Collections.Generic.List[object]]::new()
function Add-Finding($sa, $issue, $detail) {
    $Findings.Add([pscustomobject]@{
        Account = $sa.SamAccountName; UPN = $sa.UserPrincipalName; Issue = $issue; Detail = $detail
    })
}

foreach ($SA in $AD_SAs) {
    $Cloud = $BySid[$SA.SID]; $MatchType = 'SID'
    if (-not $Cloud -and $SA.UserPrincipalName) {
        $Cloud = $ByUpn[$SA.UserPrincipalName.ToLower()]; $MatchType = 'UPN'
    }
    if (-not $Cloud) {
        Add-Finding $SA '1-Missing in Entra' 'No cloud object with a matching SID or UPN.'
        continue
    }
    if ($MatchType -eq 'UPN' -and -not $Cloud.OnPremisesSyncEnabled) {
        Add-Finding $SA '1-Missing in Entra' "Only an unlinked cloud-only account with this UPN exists ($($Cloud.Id))"
    }
    if ($SA.ManagerUPN) {
        if (-not $Cloud.ManagerUPN) {
            Add-Finding $SA '2-Owner missing in Entra' "AD manager is $($SA.ManagerUPN); Entra manager is empty"
        } elseif ($Cloud.ManagerUPN.ToLower() -ne $SA.ManagerUPN.ToLower()) {
            Add-Finding $SA '2-Owner mismatch' "AD manager is $($SA.ManagerUPN); Entra manager is $($Cloud.ManagerUPN)"
        }
    }
    if (-not $SA.Enabled -and $Cloud.AccountEnabled) {
        $Why = if ($Cloud.OnPremisesSyncEnabled) {
            "Synced object has not received the disable. Last sync: $($Cloud.OnPremisesLastSyncDateTime)"
        } else {
            'Cloud-only account with matching UPN is enabled. Sync does not manage it; disable it in Entra ID.'
        }
        Add-Finding $SA '3-Disabled in AD / enabled in Entra' $Why
    }
    $AdGroupSids     = @($SA.GroupSIDs | Where-Object { $_ })
    $CloudSyncedSids = @($Cloud.MemberOfGroupSIDs | Where-Object { $_ })
    foreach ($sid in $AdGroupSids) {
        if ($SyncedGroups.ContainsKey($sid) -and $sid -notin $CloudSyncedSids) {
            Add-Finding $SA '4-Group membership mismatch' "In AD group '$($SyncedGroups[$sid].DisplayName)' but not in its cloud copy"
        }
    }
    foreach ($sid in $CloudSyncedSids) {
        if ($sid -notin $AdGroupSids) {
            Add-Finding $SA '4-Group membership mismatch' "In synced Entra group '$($SyncedGroups[$sid].DisplayName)' but not on-premises"
        }
    }
}
$Findings | Export-Csv -Path $FinalCSVReportPath -NoTypeInformation
Write-Host "Offline review complete: $($Findings.Count) findings." -ForegroundColor Yellow
if ($Findings.Count -gt 0) { $Findings | Out-GridView -Title 'Service account drift report' }

Fix 1: an account with no linked cloud object

Work out first why the account isn’t linked.

  • It’s outside sync scope. Filtered objects are deleted from Entra ID, so “missing” can be intentional. Check the account’s OU against the OUs selected in the Entra Connect wizard.
  • A cloud-only account holds the same UPN and soft match didn’t take it over. Soft match is skipped when the cloud user has an admin role, or when the tenant has BlockSoftMatchEnabled set.

For the second case you can force a hard match. Stamp the AD account’s source anchor onto the cloud user as onPremisesImmutableId, then let the next sync cycle link the two. Use the attribute your Connect installation actually uses as the source anchor:

$adUser = Get-ADUser -Identity 'svc-app01' -Properties 'mS-DS-ConsistencyGuid'
$anchorBytes = if ($adUser.'mS-DS-ConsistencyGuid') { $adUser.'mS-DS-ConsistencyGuid' }
               else { $adUser.ObjectGUID.ToByteArray() }
$immutableId = [Convert]::ToBase64String($anchorBytes)

Update-MgUser -UserId 'svc-app01@contoso.com' -OnPremisesImmutableId $immutableId

Then run a delta cycle on the Entra Connect server:

Start-ADSyncSyncCycle -PolicyType Delta

Hard match hands the cloud account to AD. Every cloud attribute that has an AD value is overwritten, and with password hash sync the cloud password is replaced too. Confirm that both objects really are the same account first.

Since July 1, 2026, Entra ID blocks a hard match when the target cloud user holds a privileged role, is eligible for one, or already has onPremisesObjectIdentifier set. Hard match also fails if the tenant has BlockCloudObjectTakeoverThroughHardMatchEnabled turned on.

Fix 2: owner missing or wrong

manager is synced from AD, so you fix it in AD. Graph rejects updates to synced properties. Set-ADUser -Manager accepts a DN, GUID, SID or sAMAccountName, not a UPN, so resolve the owner first:

$owner = Get-ADUser -Filter "UserPrincipalName -eq 'alice@contoso.com'"
Set-ADUser -Identity 'svc-app01' -Manager $owner.DistinguishedName

Then run Start-ADSyncSyncCycle -PolicyType Delta, or wait for the next scheduled cycle.

Fix 3: disabled in AD, still enabled in Entra ID

For a synced account, a disable that never arrived means sync isn’t delivering changes. Moving the account to an unsynced OU doesn’t cause this, because that deletes the cloud object. Check these in order:

  • The cycle hasn’t run yet. The default interval is 30 minutes. Compare OnPremisesLastSyncDateTime with the time the account was disabled.
  • Sync is paused. Run Get-ADSyncScheduler and check SyncCycleEnabled, StagingModeEnabled and SchedulerSuspended. The scheduler is also suspended while the Connect installation wizard is open.
  • The export was stopped by the accidental-delete threshold. When pending deletes exceed the threshold (500 by default), no objects are exported, disables included. Moving or renaming an OU can trip it. Look for event ID 116, or the stopped-deletion-threshold-exceeded status on the export run profile.

For a cloud-only look-alike, sync was never going to touch it. Disable it in Entra ID directly.

Emergency containment. Revoke sessions first, because that works for synced users too. Then disable the account where it is mastered:

$upn = 'svc-app01@contoso.com'
Revoke-MgUserSignInSession -UserId $upn

$cloudUser = Get-MgUser -UserId $upn -Property 'id,onPremisesSyncEnabled'
if ($cloudUser.OnPremisesSyncEnabled) {
    Disable-ADUser -Identity 'svc-app01'
    # On the Entra Connect server:
    # Start-ADSyncSyncCycle -PolicyType Delta
} else {
    Update-MgUser -UserId $upn -AccountEnabled:$false
}

Revoke-MgUserSignInSession invalidates refresh tokens and browser session cookies. It can take a few minutes to take effect.

Fix 4: group membership mismatch

Synced groups are mastered in AD, so make the membership change there and let it sync. If the mismatch persists after a cycle, investigate it the same way as Fix 3: sync is either paused or not exporting.

Pitfalls

  • Disabling a synced user through Graph fails. Update-MgUser -AccountEnabled:$false on a synced user returns 400 Bad Request. If your runbook calls it before Revoke-MgUserSignInSession, the revoke never runs. Revoke first, and branch on onPremisesSyncEnabled.
  • onPremisesSyncEnabled isn’t returned by default. Name it in -Property, or every user looks cloud-only.
  • Moving a dead account to an unsynced OU deletes it from the cloud. That’s usually what you want, but do it on purpose. Moving many at once can trip the accidental-delete threshold and freeze all exports, including other disables.
  • Renaming a selected OU drops it from sync scope. The next full import treats its objects as out of scope and deletes them from Entra ID. After a rename, reselect the OU in the wizard.
  • Part 2 makes two Graph calls per user. In a large tenant that is slow and can be throttled. Run it off-hours, or narrow $Users to the accounts you’re auditing before the loop.
  • AD MemberOf and Graph memberOf are both direct memberships only. Nested groups don’t show up on either side. AD MemberOf also leaves out the primary group.
  • Hard match is a takeover, not a repair tool. Don’t use it on privileged accounts. The 2026 protections block that case anyway.

Key takeaways

  • Take snapshots and compare them offline. You get audit evidence, and the comparison can be rerun without touching either directory.
  • Match on SID first and fall back to UPN. A UPN-only match to a cloud-only account is a finding.
  • For synced accounts, fix everything in AD. Graph rejects writes to synced properties, including accountEnabled and manager.
  • “Disabled in AD, enabled in Entra” points to sync not delivering changes, most often a paused scheduler or an export stopped by the accidental-delete threshold.
  • In an incident, revoke sessions first, then disable the account where it is mastered.

References

← More in Non-Human Identity