[英]How to get list of Attributes for each member of a group from Active Directory such as First Name, Last Name, Email
Here is method. 这是方法。 Please take a look at section commented as code here please. 请在此处查看评论为代码的部分。 I pass group names a string [] parameter and I am looking for attributes for the members of these groups. 我将组名称传递给string []参数,我正在寻找这些组成员的属性。
public List<Users> GetUsers(string[] groupNames)
{
List<Users> employees = new List<Users>();
string firstName = string.Empty;
string lastName = string.Empty;
string mail = string.Empty;
using (var context = new PrincipalContext(ContextType.Domain, "Name"))
{
foreach (var groupName in groupNames)
{
foreach (var userPrincipal in GroupPrincipal.FindByIdentity(context, groupName).GetMembers())
{
//code here please
employees.Add(new MPI.Domain.Entities.Users { First = firstName, Email = mail, Last = lastName });
}
}
}
return employees;
}
The GetMembers
method that you are invoking will return all members of the group including users and other groups. 您正在调用的GetMembers
方法将返回该组的所有成员,包括用户和其他组。 This is true because in active directory groups can have group members. 这是事实,因为在活动目录组中可以有组成员。
To get only users, you have to filter the members. 要仅获取用户,您必须过滤成员。 One way to do that is to use the OfType
LINQ method like this: 一种方法是使用OfType
LINQ方法,如下所示:
foreach (var userPrincipal in
GroupPrincipal
.FindByIdentity(context, groupName)
.GetMembers()
.OfType<UserPrincipal>())
{
string mail = userPrincipal.EmailAddress;
string firstName = userPrincipal.GivenName;
string lastName = userPrincipal.Surname;
employees.Add(
new MPI.Domain.Entities.Users
{
First = firstName,
Email = mail,
Last = lastName
});
}
This way, you will only go through members that are users. 这样,您只会通过用户成员。 And also the loop variable userPrincipal
would be of type UserPrincipal
(instead of the abstract Principal
class). 并且循环变量userPrincipal
也是UserPrincipal
类型(而不是抽象的Principal
类)。 So you can access the EmailAddress
, GivenName
, and the Surname
properties to access the email, first name, and the last name of the user. 因此,您可以访问EmailAddress
, GivenName
和Surname
属性以访问用户的电子邮件,名字和姓氏。
By the way, if you are interested to find the members of the group recursively, ie, you want to find the members of the groups that are members of the group, there is an overload to the GetMembers
method that allows you to do that. 顺便说一句,如果您有兴趣以递归方式找到该组的成员,即您想要找到该组成员的组成员,那么GetMembers
方法会有一个重载 ,允许您这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.