Link to home
Start Free TrialLog in
Avatar of ykkap
ykkap

asked on

Run an active directory query on users that will return the group for that user that starts with "PREF" VB.Net

Hi,

   I need to query the active directory, sending as a parameter the Username (Environment.UserName) to a function that will return me any group for that especific user that starts with "PREF" , (someting like doing a: like 'PREF%' in SQL. How can I do this function?

Thanks
Avatar of 13598
13598
Flag of United States of America image

Here is an example. For the wildcard you use asterisk. Something like:
Dim results As SearchResultCollection = Nothing

Try
    ' Bind to the users container.
    Dim path As String = "yourpath"
    Dim entry As New DirectoryEntry(path)

    ' Create a DirectorySearcher object.
    Dim mySearcher As New DirectorySearcher(entry)

    ' Set a filter for users with the name test.
    mySearcher.Filter = "(&(objectClass=user)(anr=PREF*))"

    ' Use the FindAll method to return objects to a SearchResultCollection.
    results = mySearcher.FindAll()

    ' Iterate through each SearchResult in the SearchResultCollection.
    Dim searchResult As SearchResult
    For Each searchResult In results
        ' Display the path of the object found.
        Console.WriteLine("Search properties for {0}", _
            searchResult.Path)

        ' Iterate through each property name in each SearchResult.
        Dim propertyKey As String
        For Each propertyKey In searchResult.Properties.PropertyNames
            ' Retrieve the value assigned to that property name
            ' in the ResultPropertyValueCollection.
            Dim valueCollection As ResultPropertyValueCollection = searchResult.Properties(propertyKey)

            ' Iterate through values for each property name in each SearchResult.
            Dim propertyValue As Object
            For Each propertyValue In valueCollection
                ' Handle results. Be aware that the following
                ' WriteLine() only returns readable results for
                ' properties that are strings.
                Console.WriteLine("{0}:{1}", _
                    propertyKey, _
                    propertyValue.ToString())
            Next propertyValue
        Next propertyKey
    Next searchResult
Finally
    ' To prevent memory leaks, always call
    ' SearchResultCollection.Dispose() manually.
    If Not results Is Nothing Then
        results.Dispose()
        results = Nothing
    End If
End Try
Avatar of ykkap
ykkap

ASKER

Thank you, just added to a function but I am having some errors:

Name 'results' is not declared

Name 'Accept' is not declared

Expression expected:    'Accept as Solution'

Method arguments must be enclosed in parentheses:  'Accept as Solution'

Can you please tell me how to fix those issues? thanks
PS> i am using Visual studio 2005
Here is what I use to return the directory entry for a specific user minus some things. I am unclear as to what you mean by returning any group. Can you elaborate?:
Also note:
''This code requires that you reference the .NET assembly System.DirectoryServices
for things to work.

Try
            Dim sEmailFromAddress As String = ""

            ''This code requires that you reference the .NET assembly System.DirectoryServices
            'create searcher        
            Using searcher As New DirectoryServices.DirectorySearcher()
                'get the current root which is the domain name in DC=domain format      
                'remove the DC= to just have the name      
                Dim domainName As String = searcher.SearchRoot.Name.Replace("DC=", "")

                'create a search/filter string to get that user                
                searcher.Filter = "(&(objectCategory=person)(objectClass=user)(samaccountName=" & Environment.UserName.Trim & "))"
                'find the first user that matches the filter    
                Dim result As DirectoryServices.SearchResult = searcher.FindOne
                If result IsNot Nothing Then
                   

                   
                End If
            End Using

        Catch ex As Exception
            MessageBox.Show(ex.ToString)
        End Try
Avatar of ykkap

ASKER

Thank you for your quick answer. Maybe I was unclear about what I need. We have many groups per each user in the active directory(AD). One user can be assigned to more than one group. When we see the details per each user, there is a tab in the AD that shows the groups that specific user belongs (Member of tab). Let's assume that Jhon Doe login into the PC. Knowing his userName, I want to know if the user belongs to ANY group whose name starts with "PREF". If the user belongs to a PREF group, lets say PREFITADMIN , return that group. If the user does not belong to any PREF group, return null or blank.  

Thanks
 
Try something like this (I am using a messagebox but you can change it to return that value or assign it to a global variable or whatever you need:
 Try
           
            ''This code requires that you reference the .NET assembly System.DirectoryServices
            'create searcher        
            Using searcher As New DirectoryServices.DirectorySearcher()
                'get the current root which is the domain name in DC=domain format      
                'remove the DC= to just have the name      
                Dim domainName As String = searcher.SearchRoot.Name.Replace("DC=", "")

                'create a search/filter string to get that user                
                searcher.Filter = "(&(objectCategory=person)(objectClass=user)(samaccountName=" & Environment.UserName.Trim & "))"
                searcher.PropertiesToLoad.Add("memberOf")
                searcher.PropertiesToLoad.Add("cn")
                Dim adsGrpcn As String

                'find the first user that matches the filter    
                Dim result As DirectoryServices.SearchResult = searcher.FindOne
                If result IsNot Nothing Then
                    For Each adsGrpcn In result.GetDirectoryEntry().Properties("memberof").Value
                        If adsGrpcn.ToLower.Contains("cn=pref") Then
                            MessageBox.Show(adsGrpcn)
                        End If
                    Next
                End If
            End Using

        Catch ex As Exception
            MessageBox.Show(ex.ToString)
        End Try
ASKER CERTIFIED SOLUTION
Avatar of 13598
13598
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial