If you have just an accountname and want to have the complete distiguished name:
CODE
Public Function SearchDistinguishedName(ByVal vSAN) ' Function: SearchDistinguishedName ' Description: Searches the DistinguishedName for a given SamAccountName ' Parameters: ByVal vSAN - The SamAccountName to search ' Returns: The DistinguishedName Name Dim oRootDSE, oConnection, oCommand, oRecordSet
Set oRootDSE = GetObject("LDAP://rootDSE") Set oConnection = CreateObject("ADODB.Connection") oConnection.Open "Provider=ADsDSOObject;" Set oCommand = CreateObject("ADODB.Command") oCommand.ActiveConnection = oConnection oCommand.CommandText = "<LDAP://" & oRootDSE.get("defaultNamingContext") & _ ">;(&(objectCategory=User)(samAccountName=" & vSAN & "));distinguishedName;subtree" Set oRecordSet = oCommand.Execute On Error Resume Next SearchDistinguishedName = oRecordSet.Fields("DistinguishedName") On Error GoTo 0 oConnection.Close Set oRecordSet = Nothing Set oCommand = Nothing Set oConnection = Nothing Set oRootDSE = Nothing End Function
If you have the Accountname but want to have the fully given name:
CODE
Public Function SearchGivenName(ByVal vSAN) ' Function: SearchGivenName ' Description: Searches the Given Name for a given SamAccountName ' Parameters: ByVal vSAN - The SamAccountName to search ' Returns: The Given Name Dim oRootDSE, oConnection, oCommand, oRecordSet
Set oRootDSE = GetObject("LDAP://rootDSE") Set oConnection = CreateObject("ADODB.Connection") oConnection.Open "Provider=ADsDSOObject;" Set oCommand = CreateObject("ADODB.Command") oCommand.ActiveConnection = oConnection oCommand.CommandText = "<LDAP://" & oRootDSE.get("defaultNamingContext") & _ ">;(&(objectCategory=User)(samAccountName=" & vSAN & "));name;subtree" Set oRecordSet = oCommand.Execute On Error Resume Next SearchGivenName = oRecordSet.Fields("name") On Error GoTo 0 oConnection.Close Set oRecordSet = Nothing Set oCommand = Nothing Set oConnection = Nothing Set oRootDSE = Nothing End Function
If you have the Distinguished Name and you are in need for the accountname:
CODE
Private Function SearchUserID(ByVal vDN) ' Function: SearchUserID ' Description: Searches the SamAccountName for a given DistinguishedName ' Parameters: ByVal vDN - The DistinguishedName to search ' Returns: SamAccountName Dim oConnection, oCommand, oRecordSet
Set oConnection = CreateObject("ADODB.Connection") oConnection.Open "Provider=ADsDSOObject;" Set oCommand = CreateObject("ADODB.Command") oCommand.ActiveConnection = oConnection oCommand.CommandText = "<LDAP://" & vDN & ">;;SAMAccountName" Set oRecordSet = oCommand.Execute SearchUserID = oRecordSet.Fields("sAMAccountName") oConnection.Close Set oRecordSet = Nothing Set oCommand = Nothing Set oConnection = Nothing End Function