我使用此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);
}
}
}
}
}发布于 2018-11-02 21:40:35
UserPrincipal不公开帐户的创建日期,因此您不能使用PrincipalSearcher根据该日期搜索用户。
你将不得不使用PrincipalSearcher在后台使用的DirectorySearcher -它只会给你更多的控制。
有一个用来查找计算机的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]);
}
}https://stackoverflow.com/questions/52774042
复制相似问题