vbscript get username from mail

两盒软妹~` 提交于 2019-12-23 05:29:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!