November 18, 2009

Add Uses to Group in Bulk using C#

So I had a task to take a list of usernames in a text document and add them to AD and map them to group(s). I am sure I could have done this quickly in Powershell, but I wanted to do it in C#. You can get the code here. The application is console based and uses some of our past AD classes.

The format was simple:
user1
user2
user3
A snippet of the code is below:
//using log4net;
//using ActiveDs;
public void Run()
{
foreach (AdUser user in ReadUsers())
{
using (user)
{
Dictionary userGroups = GetUserGroupsDn(user.Entry);

foreach (string groupDn in _groupsToAddUserTo.Keys)
{
if (userGroups.ContainsKey(groupDn))
continue; // User already in this group

AdGroup group = _groupsToAddUserTo[groupDn];

try
{
group.NativeObject.Add(user.Entry.Path);

log.Info(string.Format("User: {0} added to Group: {1}",
user.Entry.Properties["sAMAccountName"][0], group.NativeObject.Name));
}
catch (Exception)
{
log.Error(string.Format("User: {0} can't be added to Group: {1}. Possibly this is it's primary group already.",
user.Entry.Properties["sAMAccountName"][0], group.NativeObject.Name));
}
}
}
}
}
...and main:
 private void Run(string[] args)
{

//logging removed for brevity in snippet

Settings settings = SettingsReader.ReadFromConfig();

Adder adder = new Adder(settings);
adder.UsersToProcess = ReadUsersToProcess(settings.UsersFilePath);

adder.Run();
}
Anyone want to show how this can be done in powershell in 25 or so lines?

No comments:

Post a Comment