使用 DirectoryServices.AccountManagement,如何获取 Active Directory 安全组的电子邮件地址?

Jus*_*son 5 .net c# directoryservices active-directory

我在活动目录中有一个安全组(如下图所示),它有一个关联的电子邮件地址。如何获取群组的电子邮件地址?该GroupPrincipal对象没有任何电子邮件地址属性。

这就是我检索所有组的方式:

using (PrincipalContext context = new PrincipalContext(DirectoryContextType, Domain)) {
    using (var groupSearcher = new GroupPrincipal(context)) {
        using (var searcher = new PrincipalSearcher(groupSearcher)) {
            foreach (GroupPrincipal group in searcher.FindAll()) {
                //How do I get the e-mail address?
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

安全组

小智 6

我只是想在这里添加这个,因为我认为它可能会有所帮助。帐户管理库非常适合快速执行诸如重置 AD 用户密码或获取公共属性等操作。但它绝对没有所有这些。我所做的是获取底层目录对象,就像这样......

// Pretend you have a groupprincipal object called 'group' 
// This will get all of the properties of that group object not accounted for in 
// System.DirectoryServices.AccountManagement
DirectoryEntry groupDE = group.GetUnderlyingObject() as DirectoryEntry();
// We all know that a distro group in AD will have at least 1 email address. 
// However, A
// security group will have 0, and since the mail property is of type
// PropertyValueCollection, if you try to access the first member of the collection
// and it has no length, an exception will be thrown. The following code 
// accounts for this problem. 

// Get the mail attribute of the AD object 
PropertyValueCollection group_email_addresses = groupDe.Properties["mail"];
// Make sure there is at least one address
if (group_email_addresses.Count > 0){
   // knowing that you have at least one address, you can access the first entry or 
   // loop and grab all entries on a property, depending on the appropriate use case
   Console.WriteLine(group_email_addresses[0]); 
} 
Run Code Online (Sandbox Code Playgroud)

// 这个概念可以应用于所有的主体对象。只需查找 // GetUnderlyingObject() 方法即可开始!


Sco*_*ain 4

如果您想从帐户管理中执行此操作,您将需要创建一个公开该属性的新类

[DirectoryObjectClass("group")]
[DirectoryRdnPrefix("CN")]
public class GroupPrincipalsEx : GroupPrincipal
{
    public GroupPrincipalsEx(PrincipalContext context) : base(context) { }

    public GroupPrincipalsEx(PrincipalContext context, string samAccountName)
        : base(context, samAccountName)
    {
    }

    [DirectoryProperty("mail")]
    public string EmailAddress
    {
        get
        {
            if (ExtensionGet("mail").Length != 1)
                return null;

            return (string)ExtensionGet("mail")[0];

        }
        set { this.ExtensionSet("mail", value); }
    }
}
Run Code Online (Sandbox Code Playgroud)