Peter Hinchley

Translating a UserID into an Active Directory Distinguished Name using Name Translate

Tagged: vbscript, activedirectory

I've previously written about how to search for users in Active Directory, but if you already know the UserID of a user, it may be easier, and more efficient, to work with the user by translating the UserID into an LDAP path. This can be achieved using the IADsNameTranslate interface.

The following code provides an example of how you could use the NameTranslate interface. The script defines a group via sGroup, and a list of UserIDs via sUsers. It then employs the NameTranslate interface to convert each UserID, presented in the Windows NT format of DOMAIN\UserID, to a fully distinguished name, which is then used to add the user to the group.

The InitEx method is used to establish a connection to the global catalog, the Set method is used to define the format of the input value as Windows NT, and the Get method is used to retrieve the translated value as a distinguished name (RFC 1779).

The code is specifically written so that the connection to the global catalog, and the request that retrieves the group object, use the credentials provided in the script. This may prove helpful if the script will be running under a context that does not have the necessary permissions to interface to Active Directory.

Const ADS_NAME_INITTYPE_GC = 3
Const ADS_NAME_TYPE_NT4 = 3
Const ADS_NAME_TYPE_1779 = 1

Const USER = "administrator"
Const DOMAIN = "domain"
Const PASSWORD = "password"

sGroup = "cn=TestGroup,cn=Users,dc=domain,dc=net"
sUsers = "fsmith,fjones,jbloggs"

Set oTrans = CreateObject("NameTranslate")
oTrans.InitEx ADS_NAME_INITTYPE_GC, "", USER, DOMAIN, PASSWORD

Set oDSO = GetObject("LDAP:")
Set oGroup = oDSO.OpenDSObject("LDAP://" & sGroup, DOMAIN & "\" & USER, PASSWORD, 1)
 
cUsers = Split(sUsers,",")

For i = 0 To UBound(cUsers)
  oTrans.Set ADS_NAME_TYPE_NT4, DOMAIN & "\" & cUsers(i)
  sUserDN = "LDAP://" & oTrans.Get(ADS_NAME_TYPE_1779)
  oGroup.Add(sUserDN)
Next

The NameTranslate interface can also be used to translate canonical names, display names, user principle names, and GUIDs.

Your Say