So I have been working on a script that will import a list of GivenName and Surname to search AD for the User accounts of people displaying the table so I can confirm these are the people I want and then export a list of those users SamAccountName to a second csv. Here is the scripting I have as of now.

$users = Import-Csv 'C:\Work\NameSearch.csv'
           
foreach ($user in $users) {
$fname = $user.GivenName
$lname = $user.Surname

 
Get-ADUser -Filter {GivenName -eq $fname  -and Surname -eq $lname} -Properties * |           
select Name,GivenName,Surname,Company,Department,office,StreetAddress,City,State,PostalCode,telephonenumber,mail |
Select-Object samaccountname | 
Export-Csv 'C:\work\userid.csv' -NoTypeInformation
}

Now, when I use it as just a name search, it displays the information just fine, but when I try to export the sameaccountnames to the userid.csv it only writes the last userid from the list to the csv and I am stumped as to why. I am still learning Powershell so any clues as to what I can look at here would be greatly appreciated.

6 Spice ups

avoid using asterisk ( * ) with the properties.

e.g.

$users = Import-Csv 'C:\Work\NameSearch.csv'

$userReport =            
foreach ($user in $users) {
    $fname = $user.GivenName
    $lname = $user.Surname
    
     
    Get-ADUser -Filter {GivenName -eq $fname -and Surname -eq $lname} -Properties Name,GivenName,Surname,Company,Department,office,StreetAddress,City,State,PostalCode,telephonenumber,mail |           
    select-object Name,GivenName,Surname,Company,Department,office,StreetAddress,City,State,PostalCode,telephonenumber,mail
}

# not needed will just show you what you are looking at
$userReport

$userReport |
select-object samaccountname |
export-csv 'C:\work\userid.csv' -NoTypeInformation

3 Spice ups

If you have Export-Csv inside your ForEach loop, then the CSV file will be overwritten with each iteration. That is why you got only the last account in the file. Neally’s code uses a variable to contain the data from the loop and then outputs it to CSV once at the end. That is the most efficient way to do it.

4 Spice ups

It’s inefficient but had you put -append after your -NTI in the loop, it would have worked too.

1 Spice up

Wow, guys I figured it wouldn’t take long to find what I was screwing up but wow you guys are better than I had guessed. I hate to admit I have been banging my head on this with different variations for a little bit now. Thank you all.

@alexw @techadmin8 @garygreenberg