0

我正在尝试接收我的 AD 中的所有计算机以及当前登录的计算机。我尝试通过检查“lastLogonStamp”来执行此操作,但返回的值错误,说我的服务器在八天前登录到 AD . 即使我重新启动服务器,它也会说同样的话。我从另一个问题这里得到了代码:

如何列出所有计算机以及它们最后一次登录 AD 的时间?

public DataTable GetListOfComputers(string domain, string userName, string password)
    {
        DirectoryEntry entry = new DirectoryEntry("LDAP://" + domain,
                userName, password, AuthenticationTypes.Secure);
        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"] = DateTime.FromFileTimeUtc(long.Parse(sr.Properties["lastLogonTimestamp"][0].ToString()));
            results.Rows.Add(dr);
            de.Close();
        }

        return results;
    }
4

1 回答 1

1

如果您使用的是 .NET 3.5 及更高版本,则可以使用 aPrincipalSearcher和“按示例查询”主体进行搜索:

// create your domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// define a "query-by-example" principal - here, we search for a ComputerPrincipal 
ComputerPrincipal qbeComputer = new ComputerPrincipal(ctx);

// create your principal searcher passing in the QBE principal    
PrincipalSearcher srch = new PrincipalSearcher(qbeComputer);

// find all matches
foreach(var found in srch.FindAll())
{
    // do whatever here - "found" is of type "Principal" - it could be user, group, computer.....          
    ComputerPrincipal cp = found as ComputerPrincipal;

    if(cp != null)
    {
       string computerName = cp.Name;
       DateTime lastLogon = cp.LastLogon;
    }
}

如果您还没有 - 绝对阅读 MSDN 文章Managing Directory Security Principals in the .NET Framework 3.5,它很好地展示了如何充分利用 .NET Framework 中的新功能System.DirectoryServices.AccountManagement。或查看System.DirectoryServices.AccountManagement命名空间上的 MSDN 文档。

于 2012-05-10T18:28:08.560 回答