As written, the script is supposed to replace the mailNickname -- but I think the replace will fail if the mailNickname property has a null or empty value. If that's true, it's easy enough to handle that by ADDing the missing property:
$OUs = "OU=Users,xxx,DC=edu,DC=cn"
foreach ($OU in $OUs) {
Get-ADUser -Filter * -SearchBase $OU -Properties samAccountName, userPrincipalName, mailNickname, Enabled |
Where-Object { $_.Enabled -eq $True} |
ForEach-Object{
$parts = $_.userPrincipalName -split '@'
if ($_.mailNickname){
if ($parts[0] -ne $_.mailNickname){
$was = $_.mailNickName
Set-ADUser -Identity $_.samAccountName -Replace @{mailNickname=$parts[0]}
}
}
else{
$was = "EMPTY"
Set-ADUser -Identity $_.samAccountName -Add @{mailNickname=$parts[0]}
}
[PSCustomObject]@{
Identity = $_.samAccountName
UPN = $_.userPrincipalName
NicknameWas = $was
NickNameNow = $parts[0]
}
}
} | Export-Csv -NoType 'C:\tmp\userPrincipalName_vs_mailNickname.csv'
}