I have a CSV which I am importing, which contains a list of employeeIDs and corresponding phone numbers. I import the CSV using the importCSV commendlet.
I then want to search the $ADUsers array for matching EmployeeIDs from the imported CSV.
I can see the -contains command lets me do this:
$ADUsers.employeeid -contains "13583"
It returns true, since 13583 is listed in the array. However what I need to do, is then pull out what the corresponding sAMAccountName is for that employeeID from the $ADusers array.
Basically I am going to use the CSV (provided by a client) to set phone numbers on matching employeeIDs. Nice if they just provided an account name to begin with, but such is life.
Not sure how to do that. Please could someone kindly advise.
ForEach ( $Item in $CsvFile )
{
$ADUser = $ADUsers | Where-Object { $_.EmployeeId -EQ $Item.EmployeeId }
If ( $ADUser ) { # Set phone number or whatever based on $ADUser.SAMAccountName }
}
It might be easier to loop over the list provided by the client with the employee IDs and query the AD user objects individually instead of getting all AD user objects. Getting all objects puts more load on the domain controllers if you’ve thousands of users in your domain. The list to be updated is usually smaller than the number of users in a domain.
A couple of small updates to Daniel’s code. When you search for a user with filter, it returns NULL and does not produce a terminating error. You need to check if the user search returned something and then attempt to set the attribute:
$phoneUpdateList = Import-Csv -Path phoneupdatelist.csv
foreach ($phoneItem in $phoneUpdateList) {
$user = Get-ADUser -Filter {EmployeeID -eq $($phoneItem.EmployeeID)} -Properties employeeID, telephoneNumber, samAccountName
if ($user) {
try {
Set-ADUser -Identity $user -OfficePhone $phoneItem.Number -ErrorAction Stop
"Successfully set phone number {0} on employee {1}" -f $phoneItem.Number, $phoneItem.EmployeeID
} catch {
"Failed to set phone number {0} on {1}. {2}" -f $phoneItem.Number, $phoneItem.EmployeeID, $_.Exception
}
}
else {
"User with employee id {0} not found" -f $phoneItem.EmployeeID
}
}