【问题标题】:Find recently created Active Directory users in C#在 C# 中查找最近创建的 Active Directory 用户
【发布时间】:2018-10-12 07:03:23
【问题描述】:

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

 $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# 代码:

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);
                    }
                }
            }
        }
    }

【问题讨论】:

  • 你可以把if (user != null)改成if(p is UserPrincipal)

标签: c# active-directory principal userprincipal


【解决方案1】:

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

您将不得不使用DirectorySearcherPrincipalSearcher 无论如何都会在后台使用它 - 它只是为您提供更多控制权。

a question here 回答了这个问题,用于查找计算机,但这是适用于查找用户的代码:

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]);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    相关资源
    最近更新 更多