Skip to content

Instantly share code, notes, and snippets.

@matthewoestreich
Last active February 24, 2020 23:54
Show Gist options
  • Save matthewoestreich/01be0acac822693f897f9aa42c4bf26c to your computer and use it in GitHub Desktop.
Save matthewoestreich/01be0acac822693f897f9aa42c4bf26c to your computer and use it in GitHub Desktop.
Useful to find the last computer a user logged into, or their last logon time (NOTE: this is specific to the Domain Controller it is ran on, if you have multiple Domain Controllers you will need to run it on all of them to determine an accurate last logon time!!)
# Run this on a DC
function Get-UserLogonInfo {
param(
[Parameter(Mandatory)]
[string]$Username,
[Parameter()]
[int]$DaysAgo
)
# By default we search within the past 7 days
try {
if (-not $DaysAgo) {
$DaysAgo = 7
}
$oneDayInMilliseconds = 86400000
$timeDiff = $DaysAgo * $oneDayInMilliseconds
$filter = "*[System[EventID=4624 and TimeCreated[timediff(@SystemTime) <= $($timeDiff.ToString())]] and EventData[Data[@Name='TargetUserName']='$($Username)']]"
Get-WinEvent -LogName Security -FilterXPath $filter
} catch {
throw [Exception]::new("Something went wrong! Error: $($_)")
}
}
<# EXAMPLE
$res = Get-UserLogonInfo -Username 'User.Name' -DaysAgo 25
$res[0] | select *
#>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment