VbScript: GetObjectDN

Converts an NT user name into a Distinguished Name (object path) in Active Directory using the NameTranslate interface.

Function GetObjectDN(strObject, strDomain)
    ' Return Type: String
    '
    ' Returns a Distinguished Name for an Object from the NT SAM ID.
    ' This will only function for valid object types within an NT Domain structure.
    
    Const ADS_NAME_INITTYPE_GC = 3
    Const ADS_NAME_TYPE_1779 = 1
    Const ADS_NAME_TYPE_NT4 = 3
    
    If strDomain = "" Then
        Dim objNetwork : Set objNetwork = CreateObject("WScript.Network")
        strDomain = objNetwork.UserDomain
        Set objNetwork = Nothing
    End If
    
    On Error Resume Next : Err.Clear
    Dim objNameTranslate : Set objNameTranslate = CreateObject("NameTranslate")
    objNameTranslate.Init ADS_NAME_INITTYPE_GC, ""
    objNameTranslate.Set ADS_NAME_TYPE_NT4, strDomain & "\" & strObject
    
    Dim strObjectDN : strObjectDN = objNameTranslate.Get(ADS_NAME_TYPE_1779)
    If Err.Number 0 Then strObjectDN = ""
    Set objNameTranslate = Nothing
    On Error Goto 0
    
    GetObjectDN = strObjectDN
End Function

Usage example

strDN = GetObjectDN("Chris", "")
If strDN "" Then
    Set objUser = GetObject("LDAP://" & strDN)
End If
VbScript: GetObjectDN
Share this