0
votes

I need to update the attribute employeeID for a number of users in AD using powershell. Unfortunately, I don't have their username or samaccountname, only DisplayName. I'm able to get the users using DisplayName as a filter, but it doesn't work when using set-aduser. Is there any way I can use get-aduser to get the samaccountname, then using that to update the user via set-aduser?

Also, please note that it is important that the script doesn't overwrite any existing values.

My current (non-functional) script:

$csv = Import-Csv c:\test\users.csv

foreach ($line in $csv) {
    $ADUserObject = Get-ADUser -Filter "DisplayName -eq '$line.displayname'" -Properties employeeID 
    if ($null -eq $ADUserObject.EmployeeID) {
    Set-ADUser -Filter "DisplayName -eq '$line.displayname'" -employeeID $line.employeeid
    }
}

The CSV file looks like this:

employeeid,GivenName,Surname,displayname
489900,Angela,Davis,Angela Davis

Any input or suggestions appreciated, thank you!

1
"DisplayName -eq '$line.displayname'" -> "DisplayName -eq '$($line.displayname)'"Mathias R. Jessen
The script still fails, since -Filter cannot be used as a parameter for Set-ADuser.Joachim Hollekim
Have a look hereTheo
@JoachimHollekim use $ADUserObject |Set-ADUser ...Mathias R. Jessen

1 Answers

1
votes

As commented, this is in fact a duplicate of this question, but since there, the OP did not upvote or accept any of the given answers, I could not mark it as duplicate.

As Mathias R. Jessen explained already, the Filter you are using is wrong. Also, there is no -Filter parameter on Set-ADUser as there is on its counterpart Get-ADUser.

This should do what you want:

Import-Csv -Path 'c:\test\users.csv' | ForEach-Object {
    $ADUserObject = Get-ADUser -Filter "DisplayName -eq '$($_.displayname)'" -Properties DisplayName, employeeID -ErrorAction SilentlyContinue
    if ($ADUserObject) {
        # check if this user already has an EmployeeId filled in
        if ($ADUserObject.EmployeeID) {
            Write-Host "User $($ADUserObject.DisplayName) already has EmployeeId $($ADUserObject.EmployeeID)"
        }
        else {
            Write-Host "Setting EmployeeID $($ADUserObject.EmployeeID) for user $($ADUserObject.DisplayName)"
            $ADUserObject | Set-ADUser -EmployeeID $_.employeeid
        }
    }
    else {
        Write-Warning "User $($_.DisplayName) could not be found"
    }
}