September 9 2009

Return distinguished name of a user

This handy script is an easy way to return the DN of a user based on the sAMAccountName (aka username) that you give it. You can also provide wildcards. Usage:

cscript DNname.vbs username

eg. cscript DNname.vbs john.citizen

Will return:
“CN=john.citizen,OU=Standard,OU=Users,DC=domain,DC=com”

eg. cscript DNname.vbs john*

Will return:
“CN=john.citizen,OU=Standard,OU=Users,DC=domain,DC=com”
“CN=john.peterson,OU=Standard,OU=Users,DC=domain,DC=com”

eg. cscript DNname.vbs *john*

Will return:
“CN=john.citizen,OU=Standard,OU=Users,DC=domain,DC=com”
“CN=john.peterson,OU=Standard,OU=Users,DC=domain,DC=com”
“CN=bill.johnson,OU=Standard,OU=Users,DC=domain,DC=com”

Script is:

 On Error Resume Next
Dim objConnection, objCommand, objRootDSE, strDNSDomain
Dim strFilter, strQuery, objRecordSet, objArgs
Set objArgs = Wscript.Arguments
if objArgs.Count = 0 then
 Wscript.Echo  “CN argument required. “”*”” or “”J*”” or etc..”
 WScript.Quit (1)
End If
cn = objArgs(0)
Set objConnection = CreateObject(“ADODB.Connection”)
Set objCommand = CreateObject(“ADODB.Command”)
objConnection.Provider = “ADsDSOOBject”
objConnection.Open “Active Directory Provider”
Set objCommand.ActiveConnection = objConnection
Set objRootDSE = GetObject(“LDAP://RootDSE“)
strDNSDomain = objRootDSE.Get(“defaultNamingContext”)
strBase = “<LDAP://” & strDNSDomain & “>”
strFilter = “(&(objectCategory=person)(objectClass=user)(sAMAccountName=” & cn & “))”
strAttributes = “distinguishedName”
strQuery = strBase & “;” & strFilter & “;” & strAttributes & “;subtree”
objCommand.CommandText = strQuery
objCommand.Properties(“Page Size”) = 99999
objCommand.Properties(“Timeout”) = 300
objCommand.Properties(“Cache Results”) = False
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst
Do Until objRecordSet.EOF
    strDN = objRecordSet.Fields(“distinguishedName”)
    Wscript.Echo “””” & strDN & “”””
    objRecordSet.MoveNext
Loop
objConnection.Close
Set objConnection = Nothing
Set objCommand = Nothing
Set objRootDSE = Nothing
Set objRecordSet = Nothing



----------------------------------------------------------------------------
I use a maximum of one Google Ad per post to help offset some of my blog hosting costs.

----------------------------------------------------------------------------


Tags: , ,

Posted September 9, 2009 by danovich in category "Scripting", "Tools

Leave a Reply