Skip to main content

Get AD User Last Logon and Last Logon AD Server Script

Save this as .ps1 file and run as admin in the Domain Controller

Import-Module ActiveDirectory
 
function Get-ADUsersLastLogon()
{

  $dateinfile = (Get-Date).AddMonths(-1).ToString('yyyy-MM')
  $domain = (Get-WmiObject -Namespace root\cimv2 -Class Win32_ComputerSystem | Select Domain).Domain

  $dcs = Get-ADDomainController -Filter {Name -like "*"}
  $users = Get-ADUser -Filter * -Properties *
  $time = 0
  $exportFilePath = "c:\temp\$dateinfile - $domain - ADUser_lastLogon.csv"
  $columns = "Name,UserName,Description,AccountDisabled,CreationDate,LastLogonTime,LastLogonServer,PasswordLastSet"

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

  foreach($user in $users)
  {
    $timearray = [System.Collections.ArrayList]@()
    $rowarray = [System.Collections.ArrayList]@()
    foreach($dc in $dcs)
    { 
        $currentUser = Get-ADUser $user.SamAccountName | Get-ADObject -Server $dc.HostName -Properties lastLogon
        
        if ($currentUser.lastlogon -eq $null -or $currentUser.lastlogon -eq 0){
            $dt = 0 
        }
        else {
            $time = $currentUser.LastLogon
            $dt = [DateTime]::FromFileTime($time).ToString("dd/MM/yyyy HH:mm:ss")
        }
            $timearray.Add($dt)

        if($user.Enabled){
            $disable = "No"
        }else{
            $disable = "Yes"
        }

        if ($user.passwordlastset -eq $null){
            $pwdset = 0
        }else{
            $pwdset = $user.passwordlastset.ToString("dd/MM/yyyy HH:mm:ss")
        }

        $row = $user.SamAccountName +","+ $user.Name+","+
                $user.Description+","+ $disable+","+ 
                $user.whenCreated.ToString("dd/MM/yyyy HH:mm:ss")+","+
                $dt+","+
                $dc.Name+","+
                $pwdset+","
        $rowarray.add($row);
    }


    $newest = ($timearray | measure -Maximum).Maximum
    write-host $user.name $newest   $rowarray[$rowarray.indexof($newest)]
    Out-File -filepath $exportFilePath -append -noclobber -InputObject $rowarray[$timearray.indexof($newest)]

    $time = 0
  }
}
 
Get-ADUsersLastLogon