Export ADUser attribute

I tried this code to dump an attribute from a collection .csv and only getting the last User

Import-CSV "C:\updatedSamAccountName.csv" | % { 
$User = $_.samAccountName
Get-ADUser $User -Credential $creds -Properties EmployeeID |
Export-CSV "C:\BackupEmployeeID.csv" -NoTypeInformation

What am I doing incorrectly?

then I want to update an attribute for all of these users

Import-CSV "C:\updatedSamAccountName.csv " | % { 
$User = $_.samAccountName
$ID = $_.EmployeeID
Set-ADUser $User -employeeID $ID 

Will this update ALL the users in the .csv? I would think the forEach would ensure this.

the export-csv goes outside the loop.

second question yes. you don’t need to set variables and you don’t need the qoutes around the csv.

Import-CSV C:\updatedSamAccountName.csv | % { Get-ADUser $_.samAccountName -Properties EmployeeID} | Export-CSV C:\BackupEmployeeID.csv -NoTypeInformation

Thanks Dan, the export work.

re: Question #2 Not seeing how I will will be able to populate the employeeID with the imported csv if I don’t use the set variables for same.

If I reduce it to your suggestion:

Import-CSV "C:\updatedSamAccountName.csv " | % { 
Set-ADUser -employeeID

This will update the employeeID for all imported objects?

$_ always confuses beginners :grinning:

$_ is the object…the whole line in your csv. $_.columnheader is the specific property of that object.

So set-aduser -employeeid $_.employeeid

The issue with your Set-ADUser is it doesn’t know who to set, so you would do something like this:

foreach ($user in (Import-CSV "C:\updatedSamAccountName.csv")) {
    #You have to tell Set-ADUser who to set with Identity.  You can
    #also pipe Get-ADUser results to Set-ADUser (see below)
    Set-ADUser -Identity $user.SamAccountName -employeeID $user.EmployeeID

However, if you are doing something quick and don’t care if something fails you shouldn’t use aliases and one-liners. Take a look at this example and follow the logic:

foreach ($user in (Import-CSV "C:\updatedSamAccountName.csv")) {
    #Search for the SamAccountName in AD
    $user = Get-ADUser -Filter ("SamAccountName -eq {0}" -f $user.SamAccountName)
    #If SamAccountName is not NULL
    if ($user) {
        try {
            #We don't need to specify the Identity because we are piping the found
            #user to Set-ADUser.  In order to trap the error, we need to set ErrorAction
            #to Stop
            $user | Set-ADUser -EmployeeID $user.EmployeeID -ErrorAction Stop
        catch {
            #An error occured and we capture it
            "There was an issue setting employee ID {0} for user {1}. {2}" -f $user.EmployeeID, $user.SamAccountName, $_
    else {
        #$user is NULL, so the user wasn't found
        "{0} user not found" -f $user.SamAccountName

$user got lost between the first question and the second=D.