Script to output the LastLogon in a readable format from a list of users

Scenario: You need to determine the LastLogon date in a readable format from a list of AD users in a csv file.

Edit your users.csv file  so that row1 = name and the following rows have the SamAccountName (or other get-ADUser property) separated by a new line.

Example of contents of users.csv =

name
testusr
testuser2
testuser3
testuser4

Script:

$users = Import-csv C:\users.csv

$users | %{
$user = Get-ADUser $_.name

$dcs = Get-ADDomainController -Filter {Name -like “*”}
$time = 0
foreach($dc in $dcs)
{
$hostname = $dc.HostName
$user1 = Get-ADUser $user -Properties lastLogon
if($user1.LastLogon -gt $time)
{
$time = $user1.LastLogon
}
}
$dt = [DateTime]::FromFileTime($time)
Write-Host $user.name “last logged on at:” $dt
$x = $user.name + “:” + $dt
$x | Out-File C:\results.txt -append
}

Archives