Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get just the Enabled Accounts from Active Directory

I am using System.DirectoryServices.AccountManagement.dll to deal with Active Directory to get all the users in the "Domain Users" group.

This is returning all the users in the domain but I need to get just the enabled ones.

Here is some sample code:

List<string> users = new List<string>();

PrincipalContext pcContext = GetPrincipalContext();

GroupPrincipal grp = GroupPrincipal.FindByIdentity(pcContext,
                               IdentityType.Name,
                               "Domain Users");

foreach (Principal user in grp.GetMembers(true).OfType<UserPrincipal>())
{
    if (user.Enabled != false)
    {
        users.Add(user.Name);
    }
}

Other groups work fine, but when the group is "Domain Users", the value of the Enabled property is false for all users. This makes it impossible to distinguish between enabled and disabled users without doing a further query for each user.

like image 302
Moutasim Momani Avatar asked Jan 17 '13 14:01

Moutasim Momani


People also ask

How do I export only enabled users from Active Directory?

Complete Export AD Users to CSV ScriptGet the manager's display name or not (default true) Specify the searchBase (OU), default whole Active Directory. Get enabled or disabled accounts or both (default only enabled) Export path CSV file (default script location)

How do I export disabled users from Active Directory?

Export disabled users from OUGet all disabled users from specific OU in Active Directory and export to CSV file. You need to copy the OU distinguishedName. Paste the OU distinguishedName in the below $OU variable.


2 Answers

UserPrinciple objects have a bool Enabled property for this.

http://msdn.microsoft.com/en-us/library/system.directoryservices.accountmanagement.userprincipal_properties.aspx

// Add this to GetUserDetails
objUserDetails.EmployeeId = UserPrinical.EmployeeId;


// Then condition the add to only add enabled
if (objUserDetails.Enabled) {
    objUserDetails.Add(GetUserDetails(p.Name));
}
like image 139
Joe Petrini Avatar answered Sep 24 '22 21:09

Joe Petrini


A method around this problem could be to first search for Enabled Users using the PrincipalSearcher class and then use the Principal's method of IsMemberOf()

List<string> users = List<string>();
PrincipalContext pcContext = GetPrincipalContext();
GroupPrincipal grp = GroupPrincipal.FindByIdentity(pcContext, IdentityType.Name, "Domain Users");
UserPrincipal searchFilter = new UserPrincipal(pcContext){ Enabled = true }
PrincipalSearcher searcher = new PrincipalSearcher(searchFilter);
PrincipalSearchResult<Principal> results = searcher.FindAll();
foreach (Principal user in results)
    if (user.IsMemberOf(grp))
        users.Add(user.SamAccountName);
like image 30
Hive Avatar answered Sep 24 '22 21:09

Hive