Getting CN names from samaccounts from AD using powershell

Ramanjaneyulu Butharaju 421 Reputation points
2021-09-17T13:29:57.71+00:00

Hello Experts,

Im looking to export CN names for list of SAMaccount I have in File.

Lets say I have a txt file and it contain all the samaccounts now i want all the CN names for each samaccount in AD.

Can any one give me an idea how to write the script to query across the AD and get this CN names for my list.

Please help me with the cmdlets that can be used.

Regards,
Ram

Active Directory
Active Directory
A set of directory-based technologies included in Windows Server.
6,244 questions
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,462 questions
0 comments No comments
{count} votes

Accepted answer
  1. Limitless Technology 39,511 Reputation points
    2021-09-17T16:15:22.483+00:00

    Hello @Ramanjaneyulu Butharaju

    This should be simple:

    Import-module activedirectory
    Get-ADUser -Filter * -SearchBase "OU=Abc, DC=example, DC=com" | Select sAMAccountName, name | export-csv -Path c:\Scripts\Users.csv

    You can use other select properties from: https://social.technet.microsoft.com/wiki/contents/articles/12037.active-directory-get-aduser-default-and-extended-properties.aspx

    Like:

    Import-module activedirectory
    Get-ADUser -Filter 'Company -like "Alpha*"' -Properties * | Select -Property EmailAddress,GivenName,Surname,DisplayName,Title,Department,Office,OfficePhone,MobilePhone,Fax,StreetAddress,City,State,PostalCode,Country | Export-CSV " c:\Scripts\Users.csv" -NoTypeInformation -Encoding UTF8

    Hope this resolves your query,
    Best regards,

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. cthivierge 4,056 Reputation points
    2021-09-17T14:25:47.3+00:00

    Something like that should work...

    Create a file (C:\Temp\List_Users.txt) where you have all sAMAccountName i that file

    foreach($line in Get-Content C:\Temp\List_Users.txt) {
    Get-ADUser -Identity $line -Properties CN | Select-Object sAMAccountName,CN | Export-Csv -path C:\Temp\Export_AD_User.txt -Append
    }

    hth

    0 comments No comments