Now we'll identify orphaned groups that typically remain after removing Azure AD Connect or other synchronization tools. These groups often have specific characteristics that make them identifiable.
# Get all groups and filter for potential orphaned groups
$allGroups = Get-MgGroup -All -Property Id, DisplayName, Description, GroupTypes, SecurityEnabled, MailEnabled, OnPremisesSyncEnabled, CreatedDateTime
# Filter for groups that are likely orphaned (on-premises synced but no longer active)
$orphanedGroups = $allGroups | Where-Object {
$_.OnPremisesSyncEnabled -eq $true -and
$_.Description -like "*orphaned*" -or
$_.DisplayName -like "*_*" -or
$_.DisplayName -match "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"
}
# Display potential orphaned groups
$orphanedGroups | Select-Object DisplayName, Id, Description, CreatedDateTime | Format-Table -AutoSize
This command identifies groups with common orphaned characteristics: on-premises sync enabled, GUID-like names, or descriptions containing "orphaned".
For a more comprehensive search, check for groups with no members:
# Check for empty groups that might be orphaned
$emptyGroups = @()
foreach ($group in $allGroups) {
$memberCount = (Get-MgGroupMember -GroupId $group.Id -All).Count
if ($memberCount -eq 0) {
$emptyGroups += $group
}
}
$emptyGroups | Select-Object DisplayName, Id, CreatedDateTime | Format-Table -AutoSize
Pro tip: Always review the list manually before deletion. Some empty groups might be intentionally created for future use.