The script updates the specified property with the value of the primary SMTP address. The script can be executed in a business rule, custom command or scheduled task. In the script, the $propertyName variable specifies the LDAP name of the property to update.
PowerShell
$propertyName = "userPrincipalName" # TODO: modify me
# Get current property value
try
{
$property = $Context.TargetObject.Get($propertyName)
}
catch
{
$property = $NULL
}
# Get the current e-mail addresses
$mailboxParams = $Context.TargetObject.GetMailParameters()
$emailAddresses = $mailboxParams.EmailAddresses
$operation = "ADS_PROPERTY_NONE"
# Find the current primary address
for ($i = 0; $i -lt $emailAddresses.Count; $i++)
{
$emailAddress = $emailAddresses.GetAddress($i,[ref]$operation)
if ($emailAddress.AddressType -ne "ADM_EXCHANGE_ADDRTYPE_SMTP")
{
continue
}
if (-not($emailAddress.IsPrimary))
{
continue
}
if ($emailAddress.Address -ne $property)
{
# Update username
$Context.TargetObject.Put($propertyName, $emailAddress.Address)
$Context.TargetObject.SetInfo()
}
break
}