查找组名称所在的Active Directory组
我需要编写一个C#脚本,它返回所有具有以某个名称开头的组名的Active Directory组。 我知道可以使用以下代码返回一个组。
PrincipalContext ctx = new PrincipalContext(ContextType.Domain); GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, "Groupname");
但是,我想要Groupname所在的所有组,例如“GroupPrefix”。 然后我想使用以下代码遍历所有这些组,并将“成员”存储在我稍后可以用于搜索的数组/列表中。
foreach (UserPrincipal p in grp.GetMembers(true))
我非常感谢能得到的任何帮助。
您可以使用PrincipalSearcher
和“按示例查询”主体进行搜索:
// create your domain context using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain)) { // define a "query-by-example" principal - here, we search for a GroupPrincipal // and with the name like some pattern GroupPrincipal qbeGroup = new GroupPrincipal(ctx); qbeGroup.Name = "GroupPrefix*"; // create your principal searcher passing in the QBE principal PrincipalSearcher srch = new PrincipalSearcher(qbeGroup); // find all matches foreach(var found in srch.FindAll()) { // do whatever here - "found" is of type "Principal" } }
如果您还没有 – 绝对阅读MSDN文章.NET Framework 3.5中的管理目录安全主体,它很好地展示了如何充分利用System.DirectoryServices.AccountManagement
中的新function。 或者,请参阅System.DirectoryServices.AccountManagement命名空间上的MSDN文档 。
当然,根据您的需要,您可能希望在您创建的“按示例查询”组主体上指定其他属性:
-
DisplayName
(通常:名字+空格+姓氏) -
SAM Account Name
– 您的Windows / AD帐户名称
您可以在GroupPrincipal
上指定任何属性,并将其用作PrincipalSearcher
“按示例查询”。