How to list all computers and the last time they were logged onto in AD?
c#, directoryservices
Solution
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);
}
Problem
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; } ``` 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?