Thursday, July 3, 2008

Get list of AD group members

Quick and dirty way to do this.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.DirectoryServices;
namespace ADTest
{
public partial class Form2 : Form
{
public const string adpath = "LDAP://domain.com/";
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Boolean iresult;
iresult = GetGroupMembers(textBox2.Text);
}
public static DirectoryEntry GetDirectoryEntry()
{
DirectoryEntry de = new DirectoryEntry();
de.Path = adpath;
de.AuthenticationType = AuthenticationTypes.Secure;
return de;
}
public bool GetGroupMembers(string GroupName)
{
DirectoryEntry de = GetDirectoryEntry();
DirectorySearcher ds = new DirectorySearcher(de);
ds.Filter = "(&(objectClass=group)(cn=" + GroupName + "))";
SearchResult results = ds.FindOne();
if (results != null)
{
DirectoryEntry deGroup = new DirectoryEntry(results.Path);
System.DirectoryServices.PropertyCollection pcoll = deGroup.Properties;
int n = pcoll["member"].Count;
textBox1.Text = n.ToString();
for (int l = 0; l < n; l++)
{
DirectoryEntry deUser = new DirectoryEntry(adpath + "/" + pcoll["member"][l].ToString());
richTextBox1.Text = richTextBox1.Text + GetProperty(deUser,"givenName") + " " + GetProperty(deUser,"sn") + "\n";
deUser.Close();
}
deGroup.Close();
de.Close();
return true;
}
else
{
de.Close();
return false;
}
}
public static string GetProperty(DirectoryEntry oDE, string PropertyName)
{
if (oDE.Properties.Contains(PropertyName))
{
return oDE.Properties[PropertyName][0].ToString();
}
else
{
return string.Empty;
}
}
}
}

No comments: