Access AD Users Via Console Application

Sometimes, it's needed to look at Active Directory users and its properties.

And, sometimes you don't have a permission to access Active Directory. Its either in a different machine or you lack privileges or simply "They Dont like you in there".

To overcome the situation, it'd be wise to create a console application via C# or create a powershell script. I will be talking about how to do it developer way.
 
I won't lie. I came across the same problem and system administrators in the company was either too busy or didn't trust me having fooling around their server and Active Directory or they were probably scared I'd delete AD completely.

That's nonsense! I am an honest developer who simply wants to access their departments and report it.
 
To Access a Directory, first of all, you need to add reference or import namespaces:
  1. System.DirectoryServices  
  2. System.DirectoryServices.AccountManagement  
These 2 namespaces handle the job for you and give you the methods to access AD Users and their properties.

I'm going to give you the full source code I have developed to access a company's AD Department information and display it:

  1. using System;  
  2. using System.Collections;  
  3. using System.Collections.Generic;  
  4. using System.DirectoryServices;  
  5. using System.DirectoryServices.AccountManagement;  
  6. using System.Linq;  
  7. using System.Text;  
  8. using System.Threading.Tasks;  
  9.   
  10. namespace ADUsers {  
  11.     class Program {  
  12.         public static List<object> deps = new List<object>();               
  13.         static void Main(string[] args) {            
  14.             using (var context = new PrincipalContext(ContextType.Domain, "iersoy.com")) {  
  15.                 using (var searcher = new PrincipalSearcher(new UserPrincipal(context))) {  
  16.                     foreach (var result in searcher.FindAll()) {  
  17.                         DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;                   
  18.                         Console.WriteLine(de.Properties[""].Value);                                        
  19.                     }  
  20.                 }  
  21.             }  
  22.             List<object> depsdis = deps.Distinct().ToList();  
  23.   
  24.             foreach (var item in depsdis) {  
  25.                 Console.WriteLine(item);  
  26.             }  
  27.   
  28.             Console.ReadLine();  
  29.         }  
  30.     }  
  31. }  
This code will display all the departments from AD and display all Distinct(Unique) departments.

The reason why we are trying to get distinct departments is, sometimes a department can be assigned twice or written against case sensitivity. So its wise to get once per department for healthy results.

I hope System Administrators don't dislike you because of accessing their AD without their knowledge.


Similar Articles