c# – 如何列出所有计算机以及他们最后一次登录AD?
发布时间:2020-12-15 19:48:53 所属栏目:百科 来源:网络整理
导读:我正在尝试检索计算机名称列表以及它们上次从Active Directory登录的日期,并将它们返回到数据表中. 获取名称很容易但是当我尝试添加“lastLogon”或“lastLogonTimestamp”时,如下所示,我获得的lastLogonTimestamp的唯一值是“System._ComObject” public Da
我正在尝试检索计算机名称列表以及它们上次从Active Directory登录的日期,并将它们返回到数据表中.
获取名称很容易但是当我尝试添加“lastLogon”或“lastLogonTimestamp”时,如下所示,我获得的lastLogonTimestamp的唯一值是“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,我可以看到该属性存在并填充了数据. 解决方法
使用ComputerPrincipal类和System.DirectoryServices.AccountManagement中的PrincipalSearcher会更容易.
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); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |