Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Hello I'm stuck trying to add a function to my Windows forms program that allows a user to type in a textbox what computer or computers they would like to search for in Active Directory. The user would input the search string in a textbox then hit a button and the computers that match that search result would appear in a separate search box. Here is my code so far.

I would also like each computer name to be on a separate line such as:

computername1            
computername2        
computername3

Thanks!

This is what inside the button 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
}
like image 428
Boundinashes6 Avatar asked Aug 28 '12 05:08

Boundinashes6


1 Answers

If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:

  • Managing Directory Security Principals in the .NET Framework 3.5
  • MSDN docs on the System.DirectoryServices.AccountManagement namespace

Basically, you can define a domain context and easily find users and/or groups in 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....     
   }
}    

If you don't need to find a single computer, but search for a whole list of computers, you can use the new PrincipalSearcher interface, which basically allows you to set up a "QBE" (query-by-example) object you're looking for, defining the search criteria, and then search for matches for those criteria.

The new S.DS.AM namespace makes it really easy to play around with users and groups in AD!

like image 154
marc_s Avatar answered Oct 14 '22 23:10

marc_s