Skip to content

Compare UserPrincipalName and Primary Email Address in Active Directory and Flag Discrepancies

Compare UserPrincipalName and Primary Email Address in Active Directory

Section titled “Compare UserPrincipalName and Primary Email Address in Active Directory”

This script retrieves all Active Directory users along with their properties such as proxy addresses, userPrincipalName, and last logon timestamp. It compares each user’s userPrincipalName (UPN) with their primary email address (extracted from the proxyAddresses field). If the primary email and UPN differ, the script flags the user by adding a ChangeUPN property. The script also calculates and formats the LastLogonTimeStamp for each user. It includes optional logic to update UPNs, but this part is currently commented out.


Ideal for: Active Directory administrators maintaining user identity consistency

FeatureCapabilityBusiness Value
UPN-Email ComparisonIdentifies discrepancies between UPN and primary emailEnsures identity consistency
User FlaggingMarks users requiring UPN updatesSimplifies remediation process
Timestamp FormattingConverts file time to readable formatBetter user activity tracking
Selective ProcessingIncludes exclusion logic for specific usersFlexible deployment options

Terminal window
#$exclude = "DiscoverySearchMailbox {D919BA05-46A6-415f-80AD-7E09334BB852}","Administrator","Public Folder"
$allUsers = Get-ADUser -f * -SearchBase "CN=Users,DC=XXX-Forest,DC=local" -Properties proxyAddresses,mail,userPrincipalName,lastlogontimestamp
$Property = $allUsers | Get-Member -Type Property |Where-Object Name -ne "LastLogonTimeStamp"|Select-Object -ExpandProperty Name
$Property += @{Name="LastLogonTimeStamp";Expression={([datetime]::FromFileTime($_.LastLogonTimeStamp))}}
$allUsers = $allUsers | Select-Object -Property $Property
#$AllUsersToChangeUPN = @()
$allUsers | ForEach-Object {
#    if($_.name -notin $exclude){
        $UPN = $_.userPrincipalName
        $PEmail = $_.proxyAddresses | Where-Object {$_ -CLike "SMTP:*"}
        if($PEmail) {
            $PEmail = ($PEmail.split(':'))[1]
            if($PEmail -ne $UPN) {
                #Write-Host "UPN: $UPN diffent then Email: $PEmail"
                #$AllUsersToChangeUPN += $_
                $ChangeUPN = $true
            } else {
                $ChangeUPN = $false
            }
        }
#    }
    $_ | Add-Member -Name 'PrimaryEmail' -Value $PEmail -MemberType NoteProperty
    $_ | Add-Member -Name 'ChangeUPN' -Value $ChangeUPN -MemberType NoteProperty
}
<#
$AllUsersToChangeUPN | ForEach-Object {
    $PEmail = $_.proxyAddresses | Where-Object {$_ -CLike "SMTP:*"}
    $_ | Set-ADUser -UserPrincipalName $PEmail -WhatIf
}
$allUsers = Get-ADUser -f * -SearchBase "CN=Users,DC=xxx-Forest,DC=local" -Properties lastlogontimestamp,proxyAddresses,mail,userPrincipalName
$Property = $allUsers | Get-Member -Type Property |Where-Object Name -ne "LastLogonTimeStamp"|Select-Object -ExpandProperty Name
$Property += @{Name="LastLogonTimeStamp";Expression={([datetime]::FromFileTime($_.LastLogonTimeStamp))}}
$allUsers = $allUsers | Select-Object -Property $Property
$Now = Get-Date
$date = $Now.AddMonths(-8)
$allUsers | Where-Object LastLogonTimeStamp -lt $date | Where-Object Enabled | ft -AutoSize Name,LastLogonTimeStamp,Enabled
#>

ComponentRequirementPurpose
Active Directory ModuleActiveDirectory PowerShell moduleAccess AD user properties
AD Admin RightsRead permissions on user objectsAccess user attributes
Search Base ConfigurationCorrect OU/Domain pathTarget specific user containers
ParameterExampleDescription
SearchBase"CN=Users,DC=contoso,DC=local"Target OU for user search
Exclude ListSystem accounts, service accountsUsers to skip during processing

  1. User Retrieval

    • Get all AD users from specified SearchBase
    • Include required properties for comparison
  2. Property Preparation

    • Add formatted LastLogonTimeStamp
    • Prepare user objects for processing
  3. UPN-Email Comparison

    • Extract primary email from proxyAddresses
    • Compare with userPrincipalName
    • Flag discrepancies with ChangeUPN property
  4. Optional Updates

    • Commented code for UPN updates
    • Includes WhatIf safety testing

FieldSourceComparison Target
UserPrincipalNameAD user attributePrimary email address
Primary EmailproxyAddresses (SMTP:*)UserPrincipalName
ChangeUPN FlagBoolean resultIndicates mismatch
PropertyDescriptionUsage
PrimaryEmailExtracted primary SMTP addressComparison reference
ChangeUPNBoolean flag for mismatchesRemediation targeting
LastLogonTimeStampFormatted timestampActivity analysis

  • Identify UPN-email mismatches
  • Plan UPN standardization projects
  • Ensure proper user identity alignment
  • Prepare for Azure AD Connect sync
  • Validate user identity format
  • Pre-migration cleanup operations
  • Ensure consistent user identification
  • Support single sign-on implementations
  • Maintain directory hygiene

Key Takeaway: This script provides essential visibility into UPN-email consistency, enabling administrators to maintain proper user identity standards and support various directory synchronization and authentication scenarios.