Thursday, October 22, 2009

How to retrive a list of all computers with Last Logon time from Active Directory

I was driving myself crazy trying to retrieve the LastLogonTimestamp from Active Directory with the System.DirectoryServices namespace.
You can read here about the joy of converting the IADSLargeInteger data type (which is what the LastLogonTimestamp is) to something usable  here.
It was pointed out to me that new in .Net 3.5 is the System.DirectoryServices.AccountManagement namespace which make this task much simpler.
Here is the code that finally did the trick for me.
 

  public static DataTable GetListOfComputers(string domainName)
        {
            DataTable results = new DataTable();
            results.Columns.Add("name");
            results.Columns.Add("lastLogonTimestamp");

            PrincipalContext pc = new PrincipalContext(ContextType.Domain, domainName);
            PrincipalSearcher ps = new PrincipalSearcher(new ComputerPrincipal(pc));
            PrincipalSearchResult psr = ps.FindAll();
            foreach (ComputerPrincipal cp in psr)
            {
                DataRow dr = results.NewRow();
                dr["name"] = cp.Name;
                dr["lastLogonTimestamp"] = cp.LastLogon;
                results.Rows.Add(dr);
            }
            return results;
        }

No comments:

Post a Comment