title: Getting last Logon Time on Computers in Active Directory
body: <p><a href="https://stackoverflow.com/questions/5162897/how-can-i-get-a-list-of-users-from-active-directory">How can I get a list of users from active directory?</a></p>
  
  <p>Please see the page above. It answered most of my questions, but I get a problem when I try to get last logon time for a computer. Sorry if there was some way to comment on that page instead of making a whole new question because I didn't find such an option.</p>
  
  <pre><code>using (var context = new PrincipalContext(ContextType.Domain, "cat.pcsb.org"))
          {
              using (var searcher = new PrincipalSearcher(new ComputerPrincipal(context)))
              {
                  foreach (var result in searcher.FindAll())
                  {
                      DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
                      Console.WriteLine("Name: " + de.Properties["name"].Value);
                      Console.WriteLine("Last Logon Time: " + de.Properties["lastLogon"].Value);
                      Console.WriteLine();
                  }
              }
          }
          Console.ReadLine();
  </code></pre>
  
  <p>I replaced UserPrincipal with ComputerPrincipal. Name and some other properties work fine, but logon doesn't. I've tried doing different things like casting it to DateTime (the cast failed) but nothing worked. The above just results in System.__ComObject. So what can I do to get it to get last logon time correctly?</p>