从Active Directory中获取已启用的帐户

时间:2013-01-17 14:05:43

标签: c# active-directory directoryservices account-management

我正在使用System.DirectoryServices.AccountManagement.dll来处理Active Directory 获取“域用户”组中的所有用户。

这会返回域中的所有用户,但我只需要启用已启用的用户。

以下是一些示例代码:

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);
    }
}

其他群组工作正常,但当群组为“域用户”时,所有用户的Enabled属性值均为false。这使得无法在不对每个用户进行进一步查询的情况下区分启用和禁用用户。

2 个答案:

答案 0 :(得分:1)

UserPrinciple对象具有bool Enabled属性。

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));
}

答案 1 :(得分:0)

MSDN page of the Enabled property上有一句话:

  

如果主体未在商店中持久存在,则此属性返回null。保留主体后,默认启用设置取决于商店。 AD DS和AD LDS存储在持久化时禁用新主体,而SAM在持久化时启用新主体。应用程序只能在将该属性保留在存储中后将其设置为值。

如果默认值为false,也许它是相关的?

此外,MSDN论坛上有关于UserPrincipal.Enabled returns False for accounts that are in fact enabled?的帖子,这听起来与您的问题非常相似。根据帖子,这里可能有一个解决方案:

  

我想我误会了。无视我之前发布的内容。我想我   知道发生了什么。 GetMembers方法显然没有加载   UserPrincipal数据。我不知道是否有更好的解决方案,   但以下工作(至少在我的AD上):

foreach (UserPrincipal user in group.GetMembers(false))
{
   UserPrincipal tempUser = UserPrincipal.FindByIdentity(context, user.SamAccountName);
   // use tempUser.Enabled
   // other code here
}
相关问题