从活动目录中获取已启用帐户

本文关键字:启用 获取 活动 | 更新日期: 2023-09-27 17:54:06

我使用System.DirectoryServices.AccountManagement.dll来处理活动目录,获取"Domain users"组中的所有用户。

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

下面是一些示例代码:
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);
    }
}

其他组工作正常,但当组为"Domain Users"时,所有用户的Enabled属性值为false。如果不对每个用户进行进一步的查询,就不可能区分启用和禁用的用户。

从活动目录中获取已启用帐户

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

解决此问题的方法可以是首先使用PrincipalSearcher类搜索Enabled Users,然后使用IsMemberOf()的Principal方法

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

在MSDN页面的Enabled属性上有一个注释:

如果主体尚未保存在存储区中,则此属性返回null。主体被持久化后,默认启用的设置取决于存储。AD DS和AD LDS存储在持久化新主体时禁用它们,而SAM在持久化新主体时启用它们。应用程序只能在将此属性持久化到存储区之后将其设置为一个值。

如果默认为false,可能与此相关?

另外,在MSDN论坛上有一个关于UserPrincipal的帖子。对于实际上已启用的帐户,Enabled返回False ?这听起来和你的问题很相似。根据帖子,这里可能有一个解决方案:

我想我误解了。忽略我之前发布的内容。我想我知道发生了什么。GetMembers方法显然没有加载UserPrincipal数据。我不知道有没有更好的解决办法,但以下工作(至少在我的AD上):
foreach (UserPrincipal user in group.GetMembers(false))
{
   UserPrincipal tempUser = UserPrincipal.FindByIdentity(context, user.SamAccountName);
   // use tempUser.Enabled
   // other code here
}