[英]How to get list of Attributes for each member of a group from Active Directory such as First Name, Last Name, Email
這是方法。 請在此處查看評論為代碼的部分。 我將組名稱傳遞給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;
}
您正在調用的GetMembers
方法將返回該組的所有成員,包括用戶和其他組。 這是事實,因為在活動目錄組中可以有組成員。
要僅獲取用戶,您必須過濾成員。 一種方法是使用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
});
}
這樣,您只會通過用戶成員。 並且循環變量userPrincipal
也是UserPrincipal
類型(而不是抽象的Principal
類)。 因此,您可以訪問EmailAddress
, GivenName
和Surname
屬性以訪問用戶的電子郵件,名字和姓氏。
順便說一句,如果您有興趣以遞歸方式找到該組的成員,即您想要找到該組成員的組成員,那么GetMembers
方法會有一個重載 ,允許您這樣做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.