How to import active directory data into an array and export that into a single CSV file?

How do I export active directory data (email addresses and telephone numbers) into a single CSV file?

I have exported Active Directory data into an array and export the array into a CSV file but the CSV file is showing as empty

# Change directory to where the CSV files are located
cd "C:\Users\srobins\OneDrive - Ruralco Holdings Limited\Desktop"

# Declare an array and assign the list of users to this
$users = Get-Content users.csv

# Create an array for the active directory data to be stored
$displayname = @()

# Loop through the list of users
foreach ($user in $users) {

# Get the active directory data and store in a tempory variable
$displaynamedetails = Get-ADUser -LDAPFilter { DisplayName -eq $name }| Select name,samAccountName,OfficePhone

# Append the active direcotry data into the array
$displayname += $displaynamedetails

}

#export the array containing the list of active directory data into the new CSV
$displayname | Export-Csv "C:\SamAccountName.csv" -NoTypeInformation

I am expecting the CSV file 'SamAccountName' to be created and the list of Active Directory data is stored inside.

The CSV file is being created however, it is empty.

2 answers

  • answered 2019-06-25 06:41 Martin Lhotsky

    Parameter LDAPFilter in Get-ADUser does not use the syntax you have there.

    You need to use -LDAPFilter "(displayName=$user)" or keep existing syntax and change parameter to -Filter {DisplayName -eq $user}

  • answered 2019-06-25 07:58 Sid

    So I see that you are using a csv. Which means, Get-content is the wrong choice of cmdlet. You have to use Import-csv. Csv also means you have a header on that file.

    enter image description here

    So when you do this

    foreach ($user in $users) {
       $user
    }
    

    You will get returned data in this format through each iteration of the foreach loop.

    enter image description here

    What you need is this.

     # Change directory to where the CSV files are located
    cd "C:\Users\srobins\OneDrive - Ruralco Holdings Limited\Desktop"
    
    # Declare an array and assign the list of users to this
    $users = Import-Csv users.csv
    
    # Create an array for the active directory data to be stored
    $displayname = @()
    
    # Loop through the list of users
    foreach ($user in $users.Name) #$users.Name has to reflect the header you have. In my case it was name.
    {
    
    # Get the active directory data and store in a tempory variable
    $displaynamedetails = Get-ADUser -filter "DisplayName -eq '$user'" | Select name,samAccountName,OfficePhone #mind the '' around $user
    
    # Append the active direcotry data into the array
    $displayname += $displaynamedetails
    
    }
    
    #export the array containing the list of active directory data into the new CSV
    $displayname | Export-Csv "C:\SamAccountName.csv" -NoTypeInformation