How to programmatically search a printer in Active Directory

﹥>﹥吖頭↗ 提交于 2019-12-01 08:04:38

In contrast to users (CN=Users) there is no CN=Printers container in Active Directory after installation.

Printers are published in Active Directory in the releated computer container. What does releated computer container mean? Well, open Active Directory Users and Computers MMC snap-in and follow this procedure:

  1. Select advanced features in the view menu.
  2. Select Users, Contancts, Groups and Computers as containers in the view menu.
  3. Navigate to the computer object (which is now displayed as container) your printer belongs to.
  4. Click on the plus sign of the computer container. There you will see the printer object.

So, you see printers are published in Active Directory in the releated computer container (the printer belongs to) and not in one common container such as CN=Printers.

So, to search for a printer object in Active Directory, you have to specify a different LDAP path. For example you could specify the root of your Active Directory as the search root:

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()));
      }
    }
  }
}

Of course, you could also specify as search root the LDAP path to the computer where your printer is shared on. For example if your printer is shared on a computer called server10 and this computer is located in the CN=Computers container, then specify this LDAP path:

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

If you share a printer on the domain controller then the LDAP path is slightly different (because by default domain controller computer objects are located in the OU=Domain Controllers organizational unit):

LDAP://xxx.xxx.xxx.xxx/CN=DomainControllerName,OU=Domain Controllers,DC=domainName,DC=com
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!