Active Directory lookup for computer name (s) using user input

Hello, I am stuck trying to add a function to my Windows forms program that allows a user to enter a text field on the computer or computers that they would like to search in Active Directory. The user enters the search string in the text box, and then clicks the button, and computers matching this search result will be displayed in a separate search window. Here is my code so far.

I would also like each computer name to be on a separate line, for example:

computername1            
computername2        
computername3

Thank!

Here's what the button inside looks like:

List<string> hosts = new List<string>();
DirectoryEntry de = new DirectoryEntry();
de.Path = "LDAP://servername";

try
{
    string adser = txtAd.Text; //textbox user inputs computer to search for

    DirectorySearcher ser = new DirectorySearcher(de);
    ser.Filter = "(&(ObjectCategory=computer)(cn=" + adser + "))"; 
    ser.PropertiesToLoad.Add("name");

    SearchResultCollection results = ser.FindAll();

    foreach (SearchResult res in results) 
    //"CN=SGSVG007DC" 
    {
       string computername = res.GetDirectoryEntry().Properties["Name"].Value.ToString();
       hosts.Add(computername);
       //string[] temp = res.Path.Split(','); //temp[0] would contain the computer name ex: cn=computerName,..
       //string adcomp = (temp[0].Substring(10));
       //txtcomputers.Text = adcomp.ToString();
    }

    txtcomputers.Text = hosts.ToString();
}
catch (Exception ex)
{
    MessageBox.Show(ex.ToString());
}
finally
{
    de.Dispose();//Clean up resources
}
+5
source share
1 answer

.NET 3.5 , System.DirectoryServices.AccountManagement (S.DS.AM). :

, / AD:

// set up domain context
using(PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
   // find a computer
   ComputerPrincipal computer = ComputerPrincipal.FindByIdentity(ctx, "SomeComputerName");

   if(computer != null)
   {
       // do something here....     
   }
}    

, PrincipalSearcher, "QBE" ( ) ), , , .

S.DS.AM AD!

+7

All Articles