CodeSnip: Get a complete computer list from Active Directory using .NET 2.0
page 1 of 1
Published: 21 Apr 2006
Unedited - Community Contributed
Abstract
This article demonstrates how to use .net 2.0 to retrieve a collection of computer objects from AD.
by Web Team at ORCS Web
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 15444/ 13

 

This code sample shows how to retrieve a list of computers from Active Directory and use a For/Next to loop through the collection.  I have used this code sample on several scripts.  Using Active Directory as the authoritative source for a list of machines is very handy.  The process running this code sample normally requires a domain administrator level to retrieve this information.   

Note:   The "LDAP://DC=Steve,DC=Schofield,DC=com" is the LDAP path for the domain I am connecting to.  This represents an LDAP-based path to the Active Directory domain you are connecting to.   You will have to change the code sample to what domain you are connecting to. 

 

Code Listing 1:

   Try
    Dim enTry As System.DirectoryServices.DirectoryEntry = _
        New System.DirectoryServices.DirectoryEntry("LDAP://DC=Steve,DC=Schofield,DC=com")
    Dim mySearcherAs System.DirectoryServices.DirectorySearcher = _
        New System.DirectoryServices.DirectorySearcher(enTry)
    mySearcher.Filter = ("(objectClass=computer)")
    Dim resEntAs System.DirectoryServices.SearchResult
    For Each resEnt In mySearcher.FindAll()

      Try
                    'The reason for using the MID statement is when retrievingcomputers
                    'with this method, they are formated CN=COMPUTERNAME.   TheMID statement
                    'parses out just theComputerName.  'CN' stands for 'common name', this is 
                    'the way LDAP stores the computer variable. 
        Console.WriteLine(":Processing:" &Mid(resEnt.GetDirectoryEntry().Name.ToString(), 4))

      Catch ex As Exception
          Console.WriteLine("Trying to Connect to: " & _
            resEnt.GetDirectoryEntry().Name.ToString() & vbCrLf &ex.Message.ToString())
      End Try
    Next

   Catch
   End Try


User Comments

Title: DASDAS   
Name: DASDASD
Date: 2012-09-10 5:43:10 AM
Comment:
ADASDASD
Title: Namespace   
Name: Shoemaker
Date: 2010-09-15 12:58:06 PM
Comment:
If you cannot "Import/Uses" "System.DirectoryServices", then you need to add a reference to it for your project. It is an optional reference by default.
Title: It works fine   
Name: Usham
Date: 2010-07-22 6:45:12 AM
Comment:
Thanks buddy it works fine for me.
Title: Error while compiling   
Name: Prover
Date: 2010-03-17 6:35:42 AM
Comment:
I have an error message while running this script. It points on second string "As" word.
Title: could not get the namespace   
Name: Preet
Date: 2010-02-23 5:29:20 AM
Comment:
Thanks for the code, but "System.DirectoryServices......" could not be included, I tried to import the namespace but there isn't any.
And also would that work for a web application or due to security issues would be a window application.
Could you please explain about Domain, how to get that.
Please reply
Title: Need Working sample   
Name: bmw
Date: 2010-02-05 4:36:24 PM
Comment:
Can someone post working sample? i could not figure out from code. sorry i am new on .net stuff
Title: AD List   
Name: Thivi
Date: 2008-03-07 3:48:33 AM
Comment:
This code works really well, Thanks. All I need to know is how to bind these data (computer names, departments, rooms) into a dataset or dataview in a Windows App.
Title: AD List   
Name: JJ Campbell
Date: 2007-05-07 3:35:35 PM
Comment:
I just went back and looked at my WSH script which uses ADODB and it used ObjectCategory=user. So, I tried that in the VB8 code and it worked as well. Seems like ObjectCategory works better for me than ObjectClass.
Title: AD List   
Name: JJ Campbell
Date: 2007-05-07 3:02:25 PM
Comment:
objectCategory=person fixed it! The computers work fine either way. I guess I better do some research and see what the differance is between class and category.

Thank you for you help Steve!
jj
Title: AD List   
Name: Steve Schofield
Date: 2007-05-07 12:19:16 PM
Comment:
I'm not sure why objectClass is behaving that way, it must be something related to AD. I found a workaround that might work in your environment. It uses objectCategory. Try this out.

If rbComputers.checked Then
MySearcher.Filter = ("(objectCategory=computer)")
Else
MySearcher.Filter = ("(objectCategory=person)")
End If
Title: ad list   
Name: DJW
Date: 2007-05-07 11:23:25 AM
Comment:
I have compiled and run code, but a message in returned "referal was returned from the server"
has anyone seen this error message?
Title: AD List   
Name: JJ Campbell
Date: 2007-05-07 9:14:23 AM
Comment:
I was getting an error posting so I broke this responce into two parts. I doubt that it is our AD environment. The following WSH script returns users fine and I have another one that does computers.

'********************
'** I think the Web site doesn't like some of the vb script syntax so I stripped out the job, language and cdata stuff
'****

Sigh, I give up - I cannot get the WSH script to post.
Title: AD List   
Name: JJ Campbell
Date: 2007-05-07 9:07:01 AM
Comment:
I am using VS2005 and it should recompile everytime I save and run. Yes? I have 2 radio buttons. One for Users and one for Computers. I can toggle back and forth and refresh my list. Computers always comes up with just computers but users gets both. My code is:

'*****************
Dim strSearch As String
If tbOUName.Text = "" Then
strSearch = "LDAP://DC=alexgov,DC=net"
Else
strSearch = "LDAP://ou=" & tbOUName.Text & ",DC=alexgov,DC=net"
End If

Try
Dim objOU As System.DirectoryServices.DirectoryEntry = _
New System.DirectoryServices.DirectoryEntry(strSearch)
Dim MySearcher As System.DirectoryServices.DirectorySearcher = _
New System.DirectoryServices.DirectorySearcher(objOU)

If rbComputers.Checked Then
MySearcher.Filter = ("(objectClass=computer)")
Else
MySearcher.Filter = ("(objectClass=user)")
End If

Dim MyResult As System.DirectoryServices.SearchResult

For Each MyResult In MySearcher.FindAll()
Try
'The Substing(3) strips off the "CN=" in front of computer name
lbComputers.Items.Add(MyResult.GetDirectoryEntry().Name.Substring(3))

Catch ex As Exception
MsgBox("Trying to Connect to: " & _
MyResult.GetDirectoryEntry().Name.ToString() & vbCrLf & ex.Message.ToString())
End Try
Next
Catch
End Try
Title: AD List   
Name: Steve Schofield
Date: 2007-05-07 8:34:23 AM
Comment:
I accidentally posted 'user' object. I meant to post 'computer' object. Did you try recompiling your application and re-running. Beyond that,it must be something specific to your environment. I can not reproduce the issue.
Title: AD List   
Name: JJ Campbell
Date: 2007-05-07 7:51:07 AM
Comment:
Steve - Read what I wrote. The sample code returns a list of machines. I changed it to return users and I get users AND computers.
Title: AD List   
Name: Steve Schofield
Date: 2007-05-04 1:25:35 PM
Comment:
Hi,

That is interesting. I ran the code sample against a local AD and only returned a list of machines. You might want to try recompiling your application to ensure the reference to the 'user' object is not still hidden somewhere.

Steve
Title: AD List   
Name: JJ Campbell
Date: 2007-05-02 4:33:51 PM
Comment:
Hi the AD List runs fine for me for Computers. However, when I change the line:

mySearcher.Filter = ("(objectClass=computer)")
TO:
mySearcher.Filter = ("(objectClass=user)")

I get a list of both users AND computers all jumbled together. This has me totally mystified. Thanks for the great script and I hope you can tell me why I am getting this result.
Title: Try   
Name: Dim enTry As System.DirectoryServices.DirectoryEntry = _
Date: 2007-04-13 4:24:55 AM
Comment:
Dim enTry As System.DirectoryServices.DirectoryEntry = _
New System.DirectoryServices.DirectoryEntry("LDAP://DC=Steve,DC=Schofield,DC=com")
Dim mySearcherAs System.DirectoryServices.DirectorySearcher = _
New System.DirectoryServices.DirectorySearcher(enTry)
mySearcher.Filter = ("(objectClass=computer)")
Dim resEntAs System.DirectoryServices.SearchResult
For Each resEnt In mySearcher.FindAll()

Try
'The reason for using the MID statement is when retrievingcomputers
'with this method, they are formated CN=COMPUTERNAME. TheMID statement
'parses out just theComputerName. 'CN' stands for 'common name', this is
'the way LDAP stores the computer variable.
Console.WriteLine(":Processing:" &Mid(resEnt.GetDirectoryEntry().Name.ToString(), 4))

Catch ex As Exception
Console.WriteLine("Trying to Connect to: " & _
resEnt.GetDirectoryEntry().Name.ToString() & vbCrLf &ex.Message.ToString())
End Try
Title: Mid(resEnt.GetDirectoryEntry().Name.ToString(), 4   
Name: Mid(resEnt.GetDirectoryEntry().Name.ToString(), 4
Date: 2007-04-13 4:23:33 AM
Comment:
Mid(resEnt.GetDirectoryEntry().Name.ToString(), 4
Title: Computer descriptions   
Name: Dan
Date: 2006-12-22 4:02:12 PM
Comment:
Any was to get the computer descriptions?
Title: Computers   
Name: Steve Schofield
Date: 2006-05-09 5:40:41 PM
Comment:
Great idea. Thanks for posting the code. Never used the substring() method before except in TSQL. I am always open for easier methods of coding.

Steve
Title: Why use mid when you have Substring   
Name: Thomas Pleasance
Date: 2006-05-09 5:34:35 PM
Comment:
Try
Dim enTry As New System.DirectoryServices.DirectoryEntry("LDAP://DC=Steve,DC=Schofield,DC=com")
Dim mySearcher As New System.DirectoryServices.DirectorySearcher(enTry)
mySearcher.Filter = ("(objectClass=computer)")
For Each resEnt As System.DirectoryServices.SearchResult In mySearcher.FindAll()
Try
Console.WriteLine(":Processing:" + resEnt.GetDirectoryEntry().Name.Substring(4))
Catch ex As Exception
Console.WriteLine("Trying to Connect to: " & _
resEnt.GetDirectoryEntry().Name.ToString() & vbCrLf & ex.Message.ToString())
End Try
Next
Catch
End Try

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-03-28 2:32:10 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search