Q: How can I use a logon username to determine a user's
distinguished name (DN)?
A: The NameTranslate object can translate a username into a DN that you can use to reference an Active Directory (AD) account. Use the following steps:
- Create an instance of the NameTranslate object.
- Use the Init method to initialize the Name-Translate object.
- Pass the user s name to the NameTranslate object s Set method.
- Call the NameTranslate object's Get method to retrieve the user's DN.
Listings 1 and 2, GetDN.vbs and GetDN.js, show a VBScript and JScript version, respectively, of a GetDN function that follows these steps. Callout A in both listings illustrates the first two steps. (For more information about the parameters to the Initmethod, see the Microsoft article IADsNameTranslate::Init at http://msdn2.microsoft.com/en-us/library/aa706046.aspx.)
Next, the GetDN function determines whether the UserName parameter contains a backslash (\) character, as the code at callout B in Listings 1 and 2 shows. If the character doesn't exist (VBScript uses the InStr function, and JScript uses the indexOf method), the function assumes that you're referring to a username in the current domain and retrieves the current domain's name from the User Domain property of the WScript.Network object. The function then prefixes the username with a domain name and trailing backslash (e.g., domain\username). This step is necessary because the NameTranslate object requires the domain\username format.
The GetDN function next follows step 3 and passes the username to the NameTranslate object's Set method. If the username doesn't exist in the current domain, the Set method will fail, so the script needs to handle the error gracefully. VBScript uses the On Error Resume Next statement and JScript uses try ... catch blocks. Callout C in Listings 1 and 2 shows the error-handling process in both languages. The Set method's first parameter specifies the username's format (ADS_NAME_TYPE_NT4 or the value 3 means domain\username format), and the second parameter is the username. If the Set method fails, the function returns an empty string.
Finally, the function completes step 4 and calls the NameTranslate object's Get method, specifying DN format (ADS_NAME_TYPE_1779 or the value 1).