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
}

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: