问题描述
我想检索计算机名称的列表,以及上一次登录到Active Directory中的日期,并在一个DataTable归还。
获得的名字是很容易的,但是当我尝试添加了lastLogon或的lastLogonTimestamp如下图所示,唯一值,我得到的是的lastLogonTimestampSystem._ComObject
I am trying to retrieve a list of Computer Names and the date they were last logged onto from Active Directory and return them in a datatable.Getting the names is easy enough but when I try to add the "lastLogon" or "lastLogonTimestamp" like shown below, the only values I get for the lastLogonTimestamp is "System._ComObject"
public DataTable GetListOfComputers(string domainName)
{
DirectoryEntry entry = new DirectoryEntry("LDAP://DC=" + domainName + ",DC=com");
DirectorySearcher search = new DirectorySearcher(entry);
string query = "(objectclass=computer)";
search.Filter = query;
search.PropertiesToLoad.Add("name");
search.PropertiesToLoad.Add("lastLogonTimestamp");
SearchResultCollection mySearchResultColl = search.FindAll();
DataTable results = new DataTable();
results.Columns.Add("name");
results.Columns.Add("lastLogonTimestamp");
foreach (SearchResult sr in mySearchResultColl)
{
DataRow dr = results.NewRow();
DirectoryEntry de = sr.GetDirectoryEntry();
dr["name"] = de.Properties["Name"].Value;
dr["lastLogonTimestamp"] = de.Properties["lastLogonTimestamp"].Value;
results.Rows.Add(dr);
de.Close();
}
return results;
}
如果我使用像LDP工具查询AD我可以看到属性存在并填充数据。
我怎样才能得到这个信息?
If I query AD using a tool like LDP I can see that the property exists and is populated with data.How can I get at this info?
推荐答案
这将会是更容易使用ComputerPrincipal类和PrincipalSearcher从System.DirectoryServices.AccountManagement
It'd be easier to use the ComputerPrincipal class and a PrincipalSearcher from System.DirectoryServices.AccountManagement.
PrincipalContext pc = new PrincipalContext(ContextType.Domain, domainName);
PrincipalSearcher ps = new PrincipalSearcher(new ComputerPrincipal(pc));
PrincipalSearchResult<Principal> psr = ps.FindAll();
foreach (ComputerPrincipal cp in psr)
{
DataRow dr = results.NewRow();
dr["name"] = cp.Name;
dr["lastLogonTimestamp"] = cp.LastLogon;
results.Rows.Add(dr);
}
这篇关于如何列出的所有计算机,他们于公元已记录到什么时候?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!