Search code examples
powershellactive-directoryexport-to-csv

use samaccountnames to export user properties(mainly just first name and lastname) to csv file


I have a CSV file containing the samaccount name of some users.

From this list, I want to export the properties of these users to a CSV file.

Kindly share the simplest possible way to do so in Windows Powershell ISE.

I have tried this :

Import-ModuleActiveDirectory

Import-CSV C:\scripts\list.csv | ForEach{Get-ADUser -Identity $samaccountname-Filter*-Properties*|export-csv c:\ADusers.csv

} 

Thank you!


Solution

  • You didn't show us the first couple of lines of the CSV file. A proper CSV file has multiple fields and a header line like this:

    "AccountName","EmailAddress"
    "doe","john.doe@example.com"
    "kent","clark.kent@example.com"
    

    If this is the case, do:

    Import-ModuleActiveDirectory
    
    $userProperties = 'GivenName', 'SurName', 'Initials'
    Import-Csv -Path "C:\Scripts\List.csv" | ForEach-Object {
        $user = Get-ADUser -Filter "SamAccountName -eq '$($_.AccountName)'" -Properties $userProperties -ErrorAction SilentlyContinue
        if ($user) { 
            $user | Select-Object -Property $userProperties
        }
    } | Export-Csv "C:\ADUsers.csv"
    

    If the file you load only has SamAccountNames each listed on a new line, then this is not a CSV file and you should use:

    Import-ModuleActiveDirectory
    
    $userProperties = 'GivenName', 'SurName', 'Initials'
    Get-Content -Path "C:\Scripts\List.csv" | ForEach-Object {
        $user = Get-ADUser -Filter "SamAccountName -eq '$_'" -Properties $userProperties -ErrorAction SilentlyContinue
        if ($user) { 
            $user | Select-Object -Property $userProperties
        }
    } | Export-Csv "C:\ADUsers.csv"
    

    As you can see, I'm not using the -Identity parameter here, because in case a user with that SamAccountName is not found, an exception is thrown.
    This way, output is only generated when the user actually exists.

    Also, it is a bad idea to use -Properties * when you only want some of the properties returned.

    Hope that helps