How can I get a list of users from active directory?
请参阅上面的页面。它回答了我的大部分问题,但是当我尝试获取计算机的上次登录时间时遇到问题。抱歉,如果有某种方法可以在该页面上发表评论而不是提出一个全新的问题,因为我没有找到这样的选项。
using (var context = new PrincipalContext(ContextType.Domain, "cat.pcsb.org"))
{
using (var searcher = new PrincipalSearcher(new ComputerPrincipal(context)))
{
foreach (var result in searcher.FindAll())
{
DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
Console.WriteLine("Name: " + de.Properties["name"].Value);
Console.WriteLine("Last Logon Time: " + de.Properties["lastLogon"].Value);
Console.WriteLine();
}
}
}
Console.ReadLine();
我用 ComputerPrincipal 替换了 UserPrincipal。名称和其他一些属性工作正常,但登录不行。我试过做不同的事情,比如将它转换为 DateTime(转换失败),但没有任何效果。以上只是导致 System.__ComObject。那么我该怎么做才能让它正确获得上次登录时间?
最佳答案
为什么不直接使用 LastLogon property returned by ComputerPrincipal ? (ComputerPrincipal 是一个 AuthenicatablePrincipal)
using (var context = new PrincipalContext(ContextType.Domain, "cat.pcsb.org"))
{
using (var searcher = new PrincipalSearcher(new ComputerPrincipal(context)))
{
foreach (var result in searcher.FindAll())
{
var auth = result as AuthenticablePrincipal;
if(auth != null)
{
Console.WriteLine("Name: " + auth.Name);
Console.WriteLine("Last Logon Time: " + auth.LastLogon);
Console.WriteLine();
}
}
}
}
Console.ReadLine();
请注意,LastLogon 不是复制属性,因此如果您有多个域 Controller ,则需要查询每个 Controller 并找出谁给出了最新的结果。
关于c# - 在 Active Directory 中的计算机上获取上次登录时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19454162/