Add the specified user to specified group in Active Directory
By Perry
You can use this C# program to add specified user to specified group in active directory.
This program will add the specified user to specified group if user is not already exists. It has all the sanity checks and exception handling cases. At the and it will print the time taken for adding user to group. To pass the arguments(group and username) from command line, you will just need to change below two lines:
string privilegesGroup = "perm-group"; //Group in Active directory
string userName = "domain\\userid"; //UserID which needs to be added in the
to
string privilegesGroup = args[1]; //Group in Active directory
string userName = args[2]; //UserID which needs to be added in the
Complete C# Program:
-----------------------
using System;
using System.IO;
using System.Text;
using Microsoft.Win32;
using System.Security;
using System.Threading;
using System.Reflection;
using System.Diagnostics;
using System.Configuration;
using System.Globalization;
using System.ComponentModel;
using System.DirectoryServices;
using System.Security.Principal;
using System.Collections.Generic;
using System.Security.Permissions;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;
using System.Runtime.Remoting.Contexts;
using System.Runtime.Remoting.Messaging;
namespace DCReflactionTest
{
class Program
{
static void Main(string[] args)
{
string privilegesGroup = "perm-group"; //Group in Active directory
string userName = "domain\\userid"; //UserID which needs to be added in the specified group
string DistName = null;
object[] user_path = null;
// get the domain/host name and user name
string[] un_split = userName.Split(new char[] { '\\' });
string dhn_part = un_split[0];
string un_part = un_split[1];
int i = 0;
DirectoryEntry root = new DirectoryEntry("LDAP://RootDSE");
DirectoryEntry group = null;
SearchResult userDN, groupDN;
DirectorySearcher dsGroup, ds;
string namingContext = (string)root.Properties["defaultNamingContext"].Value;
if (namingContext == null)
namingContext = (string)root.Properties["namingContext"].Value;
//Get the timestamp
DateTime oldDate = new DateTime(2000, 1, 1);
DateTime newDate = DateTime.Now;
TimeSpan ts = newDate - oldDate;
sites[i] = sites[i].Trim();
System.Console.WriteLine("For " + sites[i]);
sites[i] = sites[i].Substring(1, sites[i].Length - 2);
System.Console.WriteLine("Site: " + sites[i]);
root = new DirectoryEntry("LDAP://" + sites[i] + "/" + namingContext);
ds = new DirectorySearcher(root,
"samAccountName=" + un_part
, null
, SearchScope.Subtree);
userDN = ds.FindOne();
dsGroup = new DirectorySearcher(root,
"samAccountName=" + privilegesGroup
, null
, SearchScope.Subtree);
groupDN = dsGroup.FindOne();
group = groupDN.GetDirectoryEntry();
if (userDN != null)
DistName = userDN.Path;
else
throw new Exception("User: " + un_part + " is not found in AD");
user_path = new object[] { DistName };
try
{
//check if user already member of the specified group
if (!bool.Parse(Convert.ToString(
group.Invoke("IsMember", user_path),
CultureInfo.CurrentCulture)))
{
if (bool.Parse(Convert.ToString(
group.Invoke("IsMember", user_path),
CultureInfo.CurrentCulture)))
System.Console.WriteLine("User Found");
try
{
group.Invoke("Add", user_path);
group.CommitChanges();
}
catch (Exception ex)
{
System.Console.WriteLine("Exception: " + ex.Message);
}
}
else
System.Console.WriteLine(user_path + " is already member of " + privilegesGroup);
}
catch (Exception ex)
{
System.Console.WriteLine("Exception: " + ex.Message);
}
newDate = DateTime.Now;
TimeSpan ts2 = newDate - oldDate;
System.Console.WriteLine("Time taken to add user: " + (ts2.TotalMilliseconds - ts.TotalMilliseconds));
System.Console.Read();
}
}
}
To remove user from group you can use/add below code:
if (group != null)
{
group.Invoke("Remove", user_path);
group.CommitChanges();
group.Close();
group.Dispose();
}
Regards,
Megha
Popularity (3171 Views)