I need to fix the below script where the goal is to set the UserprincipalName to the same as the ProxyAddress SMTP: (PrimarySMTP) entry.
$paramGetADUser = @{
Filter = "Enabled -eq 'True'"
Properties = 'EmailAddress', 'UserPrincipalName', 'SamAccountName'
SearchBase = 'OU=Users,DC=Domain,DC=com'
SearchScope = 'Subtree'
}
$ADUsers = Get-ADUser @paramGetADUser |
Where-Object { $_.UserPrincipalName -ne $_.EmailAddress } |
Select-Object Name, EmailAddress, UserPrincipalName, SamAccountName
foreach ($ADuser in $ADUsers)
{
Write-Host "Processing $($ADuser.Name)" -ForegroundColor Yellow
$paramSetADUser = @{
Identity = $ADuser.SamAccountName
UserPrincipalName = $_.EmailAddress
}
Set-ADUser @paramSetADUser
Get-ADUser -Identity $ADuser.SamAccountName |
Select-Object Name, EmailAddress, UserPrincipalName |
Format-Table -AutoSize
}
The script above somehow will reset or set the UserPrincipalName to be empty when there is no EmailAddress value, this is dangerous and NOT what I wanted.
How to prevent the issue above and achieve the standardization of UPN = PrimarySMTPAddress?