Powershell to compare AD samAccountName and mailNickname

Eaven HUANG 2,191 Reputation points
2021-07-16T03:17:59.54+00:00

Dear All,

I'm looking for a PS script where we can compare the AD users' samAccountName VS mailNickname in some specified OUs. Then if those samAccountname is not the same as mailNickname, replace the mailNickName with samAccountName.

I can get these attribute then export to excel to compare, but can it be done within PS which seems more efficient? I need to know which accounts have these non-matching attributes, before replacing them. So replacing all users' mailNickname with their samAccountName directly, that's not an ideal option.

Any idea would be really appreciated.

Windows for business | Windows Server | User experience | PowerShell
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2021-07-16T06:12:06.237+00:00

    Hi,

    Please try the below script.

    $OUs="OU=test1,DC=contoso,DC=com","OU=test2,DC=contoso,DC=com"  
    foreach ($OU in $OUs) {  
        Get-ADUser -Filter * -SearchBase $OU -Properties mailNickname | Where-Object {$_.SamAccountName -ne $_.mailNickname}  
    }  
    

    Best Regards,
    Ian Xue

    ============================================

    If the Answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.