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

2 min. readlast update: 09.26.2024

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.

Here is the script:

#$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
#>

Was this article helpful?