PowerShell: Get Last Logon for All Users Across All Domain Controllers


PowerShell: Get Last Logon for All Users Across All Domain Controllers

Here is a quick PowerShell script to help you query the last logon time for all of your users across all of your domain controllers. It will also save the output to a .csv file specified in the $exportFilePath string.

I was surprised not to find many examples of this across the web already. Either not many people have multiple DC’s necessitating this or they have another more “enterprise” way of achieving the same results. Or, I’m just missing something really obvious! Either way, it was a fun script to throw together, and I hope it saves you some time in your quest to clean up AD.

Import-Module ActiveDirectory
function Get-ADUsersLastLogon()
  $dcs = Get-ADDomainController -Filter {Name -like "*"}
  $users = Get-ADUser -Filter *
  $time = 0
  $exportFilePath = "c:lastLogon.csv"
  $columns = "name,username,datetime"

  Out-File -filepath $exportFilePath -force -InputObject $columns

  foreach($user in $users)
    foreach($dc in $dcs)
      $hostname = $dc.HostName
      $currentUser = Get-ADUser $user.SamAccountName | Get-ADObject -Server $hostname -Properties lastLogon

      if($currentUser.LastLogon -gt $time) 
        $time = $currentUser.LastLogon

    $dt = [DateTime]::FromFileTime($time)
    $row = $user.Name+","+$user.SamAccountName+","+$dt

    Out-File -filepath $exportFilePath -append -noclobber -InputObject $row

    $time = 0

More About the Author

Tim Rhymer

Systems Engineer
To Infinity and Beyond: The Power of the Cloud in IT As we hit refresh on a new month, new year and new decade, it makes sense for us to look back on the road that brought us to where we ...
How to Use Kaseya to Detect Meltdown and Spectre Vulnerable Machines To help detect client Windows machines that are vulnerable to Meltdown and Spectre at the OS and Hardware level, we built a Kaseya ...

See more from this author →

Subscribe to our newsletter

  • I understand that InterWorks will use the data provided for the purpose of communication and the administration my request. InterWorks will never disclose or sell any personal data except where required to do so by law. Finally, I understand that future communications related topics and events may be sent from InterWorks, but I can opt-out at any time.
  • This field is for validation purposes and should be left unchanged.

InterWorks uses cookies to allow us to better understand how the site is used. By continuing to use this site, you consent to this policy. Review Policy OK


Interworks GmbH
Ratinger Straße 9
40213 Düsseldorf
Geschäftsführer: Mel Stephenson

Kontaktaufnahme: markus@interworks.eu
Telefon: +49 (0)211 5408 5301

Amtsgericht Düsseldorf HRB 79752
UstldNr: DE 313 353 072