首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在C#中查找最近创建的活动目录用户

在C#中查找最近创建的活动目录用户
EN

Stack Overflow用户
提问于 2018-10-12 15:03:23
回答 1查看 569关注 0票数 0

我使用此PowerShell从Active Directory中获取过去24小时内创建的用户的信息:

代码语言:javascript
复制
 $ous = 'OU=test,DC=test,DC=local' $When = ((Get-Date).AddDays(-1)).Date $ous | ForEach { Get-ADUser -Filter {whenCreated -ge $When} -Properties whenCreated,* -SearchBase $_ }";

如何使用C#获得相同的结果?谢谢你的帮助。

下面是我的C#代码:

代码语言:javascript
复制
static void Main(string[] args)
    {
        // LDAP string to define your OU
        string ou = "OU=test,DC=test,DC=local";

        // set up a "PrincipalContext" for that OU
        using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "test.local", ou))
        {
            // define the "query-by-example" user (or group, or computer) for your search
            UserPrincipal qbeUser = new UserPrincipal(ctx);

            // set whatever attributes you want to limit your search for, e.g. Name, etc.
            qbeUser.Surname = "ilgezdi";

            // define a searcher for that context and that query-by-example 
            using (PrincipalSearcher searcher = new PrincipalSearcher(qbeUser))
            {
                foreach (Principal p in searcher.FindAll())
                {
                    // Convert the "generic" Principal to a UserPrincipal
                    UserPrincipal user = p as UserPrincipal;

                    if (user != null)
                    {
                        console.Write(user);
                    }
                }
            }
        }
    }
EN

回答 1

Stack Overflow用户

发布于 2018-11-02 21:40:35

UserPrincipal不公开帐户的创建日期,因此您不能使用PrincipalSearcher根据该日期搜索用户。

你将不得不使用PrincipalSearcher在后台使用的DirectorySearcher -它只会给你更多的控制。

有一个用来查找计算机的a question here,但这是用来查找用户的代码:

代码语言:javascript
复制
var domainRoot = new DirectoryEntry("LDAP://rootDSE");
string rootOfDomain = domainRoot.Properties["rootDomainNamingContext"].Value.ToString();
var dsSearch = new DirectorySearcher(rootOfDomain);

//Set the properties of the DirectorySearcher
dsSearch.Filter = "(&(objectClass=user)(whenCreated>=" + dateFilter.ToString("yyyyMMddHHmmss.sZ") + "))";
dsSearch.PageSize = 2000;
dsSearch.PropertiesToLoad.Add("distinguishedName");
dsSearch.PropertiesToLoad.Add("whenCreated");
dsSearch.PropertiesToLoad.Add("sAMAccountName");

//Execute the search
using (SearchResultCollection usersFound = dsSearch.FindAll()) {
    foreach (SearchResult user in usersFound) {
        Console.WriteLine(user.Properties["sAMAccountName"][0]);
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52774042

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档