The formatting of this code is not very good, it came from an online website. I plan to simplify it later on.
Copy to Clipboard
Import-Module ActiveDirectory
function Get-LastLogonEvents
{
$dcs = Get-ADDomainController -Filter {Name -like "*"}
$users = Get-ADUser -Filter *
$time = 0
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)
Write-Host $dt " was the last login for " $currentUser.Name
$time = 0
}
}
}
Get-LastLogonEvents
|