Tuesday, November 24, 2009

Listing User Last Logon with Powershell

This script assumes that you have enabled auditing on successful logins (by default, it doesn't).

The general process it follows is:
  • retrieve the Security event log
  • pulls login information up to the last reboot
  • gets unique usernames and the time they logged in
  • writes it all out to a text file
It's still a little raw, but it works. It runs very slow over the network; I'll work up one that uses the PSJob facilities...


function getLastBoot( $computername )
{
$wmi = Get-WmiObject -Class Win32_OperatingSystem
return $wmi.ConvertToDateTime( $wmi.LastBootUpTime )
}

function getTopDates()
{
$logins = @()
$input | foreach {
$rec = $_

# this is ugly...I'm going thru the list twice
$hasit = ($logins | where {($_.UserName -eq $rec.UserName) -and ($_.MachineName -eq $rec.MachineName)})

if( $hasit )
{
for( $x = 0; $x -lt $logins.Count; $x++ )
{
if(($rec.UserName -eq $logins[ $x ].UserName ) -and
($rec.MachineName -eq $logins[ $x ].MachineName ))
{
$logins[ $x ] = $rec
}
}
}
else
{
$logins = $logins + @(,$rec)
}
}
return $logins
}

$start_time = (Get-Date)
Write-Host "starting all $start_time"

$target_computers = @( "dal1mspwb16",
"dal1mspwb19",
"dal1mspwb36",
"dal1mspwb37",
"dal1mspwb12",
"dal1mspwb35")

# $target_computers = @( "dal1msdwb34" )

$target_computers | foreach {
$target = $_
$lastboot = getLastBoot( $target )

Remove-Item "iis_logins_$target.txt" -ErrorAction SilentlyContinue


Write-Host "processing $target :" (get-date)
Get-EventLog -LogName "Security" -ComputerName $target -After $lastboot |
select -Property UserName, MachineName, TimeGenerated -Unique |
sort -Property TimeGenerated |
getTopDates |
Out-File -Append -FilePath "iis_logins_$target.txt"

Write-Host "completed $target :" (get-date)
}

$end_time = (Get-Date)

Write-Host "complete"
Write-Host "Started: $start_time"
Write-Host "Finished: $end_time"
Write-Host ($end_time - $start_time)

No comments:

Post a Comment