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
ykkapAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

13598Commented:
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
0
ykkapAuthor Commented:
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
0
13598Commented:
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
0
Cloud Class® Course: Microsoft Exchange Server

The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.

ykkapAuthor Commented:
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
 
0
13598Commented:
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
0
13598Commented:
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      
                                '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
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.