如何以编程方式在Active Directory中搜索打印机

时间:2012-05-06 04:38:00

标签: c# active-directory printers

尝试使用C#在Active Directory中查找打印机/共享。

这是我的示例代码,适用于用户但是我看不到能够找到使用相同概念的打印机。 (我是Active Directory的新手)。

    DirectoryEntry entry = new DirectoryEntry();
    entry.Path = "LDAP://xxx.xxx.xx.xx/CN=Printers;DC=domainName, DC=com";
    entry.Username = @"domainName.com\Administrator";
    entry.Password = "admin";

    DirectorySearcher search = new DirectorySearcher(entry);
    search.Filter = "(objectCategory=printQueue)";
    SearchResult result = search.FindOne();

    if (result != null)
    {
        ResultPropertyCollection fields = result.Properties;

        foreach (String ldapField in fields.PropertyNames)
        {

            foreach (Object myCollection in fields[ldapField])
                Console.WriteLine(String.Format("{0,-20} : {1}",
                              ldapField, myCollection.ToString()));
        }
    }

非常感谢任何协助。

1 个答案:

答案 0 :(得分:5)

与用户(CN=Users)相比,安装后Active Directory中没有CN=Printers容器。

打印机在相关计算机容器中的Active Directory中发布。是什么 相关的电脑容器意味着什么好吧,打开Active Directory用户和计算机MMC管理单元和 请遵循以下程序:

  1. 在视图菜单中选择高级功能。
  2. 在视图菜单中选择“用户”,“连续”,“组和计算机”作为容器。
  3. 导航到计算机对象(现在显示为容器) 您的打印机属于。
  4. 单击计算机容器的加号。在那里你会看到 打印机对象。
  5. 因此,您会看到打印机在相关计算机容器(打印机所属)中的Active Directory中发布,而不是在CN=Printers这样的常见容器中发布。

    因此,要在Active Directory中搜索打印机对象,您必须指定 不同的LDAP路径。例如,您可以指定Active Directory的根目录 作为搜索根:

    using (DirectoryEntry entry = new DirectoryEntry())
    {
      entry.Path = "LDAP://xxx.xxx.xxx.xxx/DC=domainName,DC=com";
      entry.Username = @"domainName.com\Administrator";
      entry.Password = "SecurePassword";
    
      using (DirectorySearcher search = new DirectorySearcher(entry))
      {
        search.Filter = "(objectCategory=printQueue)";
        SearchResult result = search.FindOne();
    
        if (result != null)
        {
          ResultPropertyCollection fields = result.Properties;
    
          foreach (String ldapField in fields.PropertyNames)
          {
            foreach (Object myCollection in fields[ldapField])
              Console.WriteLine(String.Format("{0,-20} : {1}",
                              ldapField, myCollection.ToString()));
          }
        }
      }
    }
    

    当然,您也可以将搜索根指定为打印机所在计算机的LDAP路径 分享。例如,如果您的打印机在名为server10的计算机上共享,并且此计算机位于CN=Computers容器中,请指定此LDAP路径:

    LDAP://xxx.xxx.xxx.xxx/CN=server10,CN=Computers,DC=domainName,DC=com
    

    如果您在域控制器上共享打印机,那么LDAP路径会略有不同(因为默认情况下,域控制器计算机对象位于OU=Domain Controllers组织单位中):

    LDAP://xxx.xxx.xxx.xxx/CN=DomainControllerName,OU=Domain Controllers,DC=domainName,DC=com