使用用户输入在Active Directory中搜索计算机名称

Bou*_*es6 6 c# active-directory

您好,我试图在我的Windows窗体程序中添加一个函数,该函数允许用户在文本框中键入他们想要在Active Directory中搜索的计算机或计算机.用户将在文本框中输入搜索字符串,然后点击按钮,与该搜索结果匹配的计算机将显示在单独的搜索框中.到目前为止,这是我的代码.

我还希望每个计算机名称都在一个单独的行上,例如:

computername1            
computername2        
computername3
Run Code Online (Sandbox Code Playgroud)

谢谢!

这是按钮内部的样子:

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
}
Run Code Online (Sandbox Code Playgroud)

mar*_*c_s 8

如果您使用的是.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....     
   }
}    
Run Code Online (Sandbox Code Playgroud)

如果您不需要查找单个计算机,但搜索整个计算机列表,则可以使用新PrincipalSearcher界面,这基本上允许您设置"QBE"(按示例查询)对象寻找,定义搜索条件,然后搜索这些条件的匹配项.

新的S.DS.AM使得在AD中与用户和群组玩游戏变得非常容易!