Search code examples
powershellactive-directoryadsi

Cannot set manager attribute using ADSI in PowerShell


I update some user information in AD from an HR database.

Text fields or the photo works fine:

$user.Put("telephoneNumber", "1234")
$user.Put("thumbnailPhoto", $binaryfile)
$user.SetInfo()

But I also have to set the manager and tried

$user.Put("manager", "MYDOMAIN\MYUSERNAME")

or

$user.Put("manager", "MYUSERNAME")

That gives the following error:

Exception calling "setinfo" with "0" argument(s): "An invalid dn syntax has been specified."

What's the correct syntax to update the manager using ADSI?


Solution

  • As the error message suggests: the manager attribute expects a distinguished name (dn), not a user logon name, so you need to get the manager's dn first and then put that value into the manager attribute.

    $manager = 'MYUSERNAME'
    
    #...
    
    $searcher = New-Object DirectoryServices.DirectorySearcher(([adsi]''))
    $searcher.Filter = "(&(objectClass=user)(objectCategory=person)(sAMAccountName=${manager}))"
    $dn = $searcher.FindOne().Properties['distinguishedName'][0]
    
    #...
    
    $user.Put('manager', $dn)
    $user.SetInfo()