Home > Software engineering >  Set-ADUser -Manager entity with Contact
Set-ADUser -Manager entity with Contact

Time:12-03

I have a csv with the following fields:

User | AD_Manager_ID | Dyn_Manager_ID [email protected] | 1234 | 1455

The Dyn_Manager_ID field is the employeeID of another user. 99% of the time it corresponds to an actual user, but sometimes it corresponds to a contact

I can get the contact like this:

Get-ADObject -Filter "employeeID -eq '1455'"

but when I try to Set-ADUser -Manager with that object, it returns a 'Cannot find an object with idenity" error.

Here is the code for regular users (non contacts):

$csvimport = import-csv -Path C:\Users\ME\Desktop\AccountChangesCSV.csv
foreach ($User in $csvimport)
{
  Get-aduser -filter "employeeID -eq '$($user.DYN_Mgr_ID)'" | select-object samaccountname - 
OutVariable ManagersName

Get-ADUser -Filter "employeeID -eq '$($user.AD_ID)'" | set-aduser -Manager 
$ManagersName.samaccountname
}

CodePudding user response:

If someone's manager could be either another user or a contact, then do not use Get-ADUser to find the manager object, but Get-ADObject instead.

If this was a contact, there is no SamAccountName property, but instead, you can use the DistinguishedName or the ObjectGUID

Try

$csvimport = Import-Csv -Path 'C:\Users\ME\Desktop\AccountChangesCSV.csv'
foreach ($user in $csvimport) {
    $manager = Get-ADObject -Filter "employeeID -eq '$($user.DYN_Mgr_ID)'" -ErrorAction SilentlyContinue
    if ($manager) {
        # now update the users Manager property with the DistinguishedName of the manager object
        Get-ADUser -Filter "employeeID -eq '$($user.AD_ID)'" | 
        Set-ADUser -Manager $manager.DistinguishedName  # or ObjectGUID instead of DistinguishedName
    }
}

This works for both AD user objects and contacts alike

CodePudding user response:

I think this post has the answer: updating an ADUser's Manager with a contact card

This is the code that finally worked for me:

$csvimport = Import-Csv -Path 'C:\Users\ME\Desktop\AccountChangesCSV.csv'
foreach ($user in $csvimport) {
$manager = Get-ADObject -Filter "employeeID -eq '$($user.DYN_Mgr_ID)'" - 
ErrorAction SilentlyContinue
if ($manager) {
    # now update the users Manager property with the DistinguishedName of the 
manager object
    $aduser = Get-ADUser -Filter "employeeID -eq '$($user.AD_ID)'"
    Set-AdUser -Identity $aduser.SamAccountName  -replace 
@{manager="$($manager.distinguishedname)"}
    }
}
  • Related