Monday, June 14, 2010

Using C# to find all CNs in ActiveDirectory

Usage:

To list all computers on the network where Microsoft Active Directory is used.

I faced this problem when I wished to document all computers in the local domain of this company. I found J.O.Donnell's C# solution posted on Auguest 27, 2002. I modified it to make it more flexiable to our case.


Discription:

In Active Directory there is an OU or Organizational Unit. It is actually a folder with a category of computers inside. I assumed that each computer has a LDAP path which is something like LDAP://domain OU=Workstations CN=localhost. In my design I will read all CNs in a specific domain with or without given OU.

The C# solution is straight forward. I always like a simple answer.


Execution:

C:> ListCN.exe domain contains notContains

E.g. Use the command bellow to find out all non-obsoleted Workstations and Servers in the domain of MFCHINA:

C:> ListCN.exe MFCHINA Workstations;Servers Obsoleted

//ListCN //Displays all computer names in an Active Directory //Written 08/26/02 - John O'Donnell - csharpconsulting@hotmail.com //Modified 06/14/10 - River Liu - output all workstations in certain LDAP
using System; using System.DirectoryServices; using Microsoft.Office.Core; using Microsoft.CSharp; using Excel = Microsoft.Office.Interop.Excel; using System.Collections.Generic; using System.Text; namespace ActiveDirectorySearch1 { class Class1 { static void Main (string[] args) { String domain=""; String contain=""; String notContain=""; if (args.Length <= 0) Environment.Exit(-1); else { domain = args[0]; } if (args.Length >= 2) { contain = args[1]; } if (args.Length >= 3) { notContain = args[2]; } String ldap = "LDAP://" + domain; String[] contains = contain.Split(';'); String[] notContains = notContain.Split(';'); DirectoryEntry entry = new DirectoryEntry(ldap); DirectorySearcher mySearcher = new DirectorySearcher(entry); mySearcher.Filter = ("(objectClass=computer)"); Console.WriteLine("Listing of computers in the Active Directory"); Console.WriteLine("============================================");
foreach(SearchResult resEnt in mySearcher.FindAll()) { String path = resEnt.GetDirectoryEntry().Path.ToString(); String cn; Boolean contained = true; Boolean containedNot = false; foreach (string con in contains) { if (String.Compare(con, "") == 0); else contained &= path.Contains(con); } foreach (string notCon in notContains) { if (String.Compare(notCon, "") == 0); else containedNot |= path.Contains(notCon); } if (contained == true && containedNot == false) { cn = resEnt.GetDirectoryEntry().Name.ToString(); cn = cn.Substring(3); Console.WriteLine(cn); using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"CNlist.inf", true)) { file.WriteLine(cn); //file.WriteLine(cn + "," + path); } } } Console.WriteLine("=========== End of Listing ============="); } } }

0 comments:

Post a Comment