问题
It is possible to get the username from active directory by query the email address ? Query the email address by username its no problem like this:
Set objSysInfo = CreateObject("ADSystemInfo")
Set WshShell = CreateObject("WScript.Shell")
strUser = objSysInfo.UserName
Set objUser = GetObject("LDAP://" & strUser)
strEMail = objUser.mail
But in my scenario I have only the email and no username.
Thanks for helping
回答1:
I don't think you can do it off LDAP directly.
It's faster to create a query and extract exactly what you are after (sAMAccountName):
UserNameFromEmail "Firstname.Lastname@YourDomain.com"
Sub UserNameFromEmail(sEmail)
Const ADS_SCOPE_SUBTREE = 2
Const PageSize = 1000
Dim sRootLDAP, oConnection, oCommand, oRecordSet
sRootLDAP = "'LDAP://" & GetObject("LDAP://RootDSE").Get("defaultNamingContext") & "'"
Set oConnection = CreateObject("ADODB.Connection")
oConnection.Provider = "ADsDSOObject"
oConnection.Open "Active Directory Provider"
Set oCommand = CreateObject("ADODB.Command")
Set oCommand.ActiveConnection = oConnection
oCommand.CommandText = "Select sAMAccountName from " & sRootLDAP & " Where mail='" & sEmail & "'"
oCommand.Properties("Page Size") = PageSize
oCommand.Properties("Timeout") = 30
oCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
oCommand.Properties("Cache Results") = True
Set oRecordSet = oCommand.Execute
oRecordSet.MoveFirst
Do Until oRecordSet.EOF
WScript.Echo "Username for """ & sEmail & """ is """ & oRecordSet.Fields(0) & """"
oRecordSet.MoveNext
Loop
Set oRecordSet = Nothing
Set oCommand = Nothing
Set oConnection = Nothing
End Sub
来源:https://stackoverflow.com/questions/23843380/vbscript-get-username-from-mail