Export to CSV - It Writes Only Last Row

My friends,
I am having trouble exporting to a CSV file. Only the last row is written to the export file, Only the last one.
I would like to import a CSV file of CN Names and
Find the names in Active Directory and get SamAccountName, mail and
Export to a CSV File.

Import File: C:\Folderx\BulkShort.cvs
User
Hun, Atilla
Borden, Lizzie
Capone, Al

Results, I get results for only the last row of the import file.
Export File:
C:\Folderx\Sammail.cvs
SamAccountName Mail
Al.Capone Al.Capone@Atlanta.com

Here’s the script:

  Import-Csv -Path "C:\Folderx\BulkShort.csv" |           
foreach {           
 Get-ADUser -SearchBase "OU=users,OU=Defense,OU=Agencies,DC=Fed,DC=net" -Filter "cn -like '*$($_.user)*'" -Properties * | select SamAccountName, mail |   
  Export-Csv -Path C:\Folderx\Sammail.csv 
}

If I don’t use the -searchbase, it runs for hours with two-hundred names because our Active Directory is so big.
Thanks in advance,

Actually it does write all of the accounts to the CSV file but since you have the export inside the loop it overwrites each one of them except of the last one.

To circumvent this you could simply add the paramter -Append to your Export-Csv command. A better option would be to move the export outside the loop.

$SearchBase = 'OU=users,OU=Defense,OU=Agencies,DC=Fed,DC=net'

Import-Csv -Path 'C:\Folderx\BulkShort.csv' |
    ForEach-Object {           
        Get-ADUser -SearchBase $SearchBase -Filter "cn -like '*$($_.user)*'" -Properties mail  | 
            Select-Object sAMAccountName, mail 
    }|   
        Export-Csv -Path 'C:\Folderx\Sammail.csv' 

Olaf, Thank you. Yes, that works. I looked for hours but for some reason, I could not find the simple solution.
My co-worker and I will be adding to this script to modify some Attributes, moving the record to a different OU and disabling the records. We decided to write this script because four or five times per year we get a bulk request with hundreds of names.
I will keep you informed.
Many Thanks, Olaf

Great. I’m glad it helped. :+1:t4:

You may mark my answer as the solution. This might help others looking for the same or a similar problem finding the solution a little quicker. :wink: