Query User in AD and Display details in an output object (e.g. label) RRS feed

  • Question

  • Please help, I am trying to query a user from AD by means of SAMAccountName and display important information such as Full name, Logon Name, Email, expiration date, and the likes on a label or any VB container/output object.
    Any ideas, or a sample code for this
    Any help will be much appreciated.
    Friday, October 6, 2017 2:26 AM

All replies

  • The first Google link gives :

    Utiliser VB.NET et Active Directory

    (it is in french but the code should be sufficient...)

    Friday, October 6, 2017 5:15 AM
  • The below code should get you started. You can either provide a login ID to the function or it will get the login ID of the currently authenticated user and perform the AD lookup. There are many user attributes and I've listed a few. Some can be retrieved directly while others require a little more work. If there are any you are having trouble with then post a follow-up.

        Public Function GetUserInfo(ByVal UserID As String)
            Dim RootDSE As New DirectoryServices.DirectoryEntry("LDAP://RootDSE")
            Dim DomainDN As String = RootDSE.Properties("DefaultNamingContext").Value
            Dim ADEntry As New DirectoryServices.DirectoryEntry("LDAP://" & DomainDN)
            Dim ADSearch As New System.DirectoryServices.DirectorySearcher(ADEntry)
            If UserID = "" Then
                UserID = System.Security.Principal.WindowsIdentity.GetCurrent.Name.Split("\"c)(1)
            End If
            ADSearch.Filter = ("(samAccountName=" & UserID & ")")
            ADSearch.SearchScope = SearchScope.Subtree
            Dim UserFound As SearchResult = ADSearch.FindOne()
            Dim propertyCount As Integer = UserFound.Properties("memberOf").Count
            If Not IsNothing(UserFound) Then
                Dim DirectoryEntry As DirectoryEntry = UserFound.GetDirectoryEntry
                Dim propertyCounter As Integer
                Dim dn As String
                For propertyCounter = 0 To propertyCount - 1
                    dn = UserFound.Properties("memberOf")(propertyCounter).ToString.Split(",")(0).Remove(0, 3)
                Dim Attrib As String = "msDS-User-Account-Control-Computed"
                Dim User As DirectoryEntry
                User = UserFound.GetDirectoryEntry()
                User.RefreshCache(New String() {Attrib})
                Const UF_LOCKOUT As Integer = &H10
                Dim Flags As Integer = CInt(Fix(User.Properties(Attrib).Value))
                If Convert.ToBoolean(Flags And UF_LOCKOUT) Then
                    Console.WriteLine("Account is locked out")
                    Console.WriteLine("Account is not locked out")
                End If
            End If
        End Function

    Paul ~~~~ Microsoft MVP (Visual Basic)

    Friday, October 6, 2017 1:02 PM