Skip to content

Instantly share code, notes, and snippets.

@ShawInnes
Created January 30, 2016 07:00
Show Gist options
  • Save ShawInnes/ef2226f691a01a42d48b to your computer and use it in GitHub Desktop.
Save ShawInnes/ef2226f691a01a42d48b to your computer and use it in GitHub Desktop.
Some AD Querying Magic
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.DirectoryServices;
namespace ADQuery
{
class Program
{
static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.WriteTo.LiterateConsole()
.MinimumLevel.Debug()
.CreateLogger();
try
{
DirectoryEntry ldapConnection = new DirectoryEntry();
ldapConnection.Path = "LDAP://DC=dmz,DC=local";
ldapConnection.AuthenticationType = AuthenticationTypes.Secure;
DirectorySearcher search = new DirectorySearcher(ldapConnection);
search.Filter = "(&(objectClass=user))";
//search.PropertiesToLoad.Add("cn");
SearchResultCollection allUsers = search.FindAll();
foreach (SearchResult result in allUsers)
{
DirectoryEntry entry = result.GetDirectoryEntry();
var dn = entry.Properties["distinguishedName"].Value;
var props = Newtonsoft.Json.JsonConvert.SerializeObject(result.Properties);
Log.Information("Common Name {cn} {props}", result.Properties["cn"][0].ToString(), props);
}
}
catch (Exception e)
{
Log.Error(e, "Exception caught: {message}" + e.ToString());
}
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment