Skip to content

Instantly share code, notes, and snippets.

@royashbrook
Created April 19, 2023 19:40
Show Gist options
  • Save royashbrook/c2d6f75c94ca6497d84933982e4e0421 to your computer and use it in GitHub Desktop.
Save royashbrook/c2d6f75c94ca6497d84933982e4e0421 to your computer and use it in GitHub Desktop.
show logon logoff events for current domain. easier to run from a domain controller.
$Username = "rashbrook" # Replace with the target user's username
$LogName = "Security"
$LogonEventID = 4624
$LogoffEventID = 4634
# Load the Active Directory module
Import-Module ActiveDirectory
# Get the list of domain controllers
$DomainControllers = Get-ADDomainController -Filter *
ForEach ($DC in $DomainControllers) {
$DCName = $DC.HostName
Write-Host "Checking domain controller: $DCName"
$XPathQuery = "*[System[EventID=$LogonEventID or EventID=$LogoffEventID] and EventData[Data[@Name='TargetUserName']='$Username']]"
try {
$Events = Get-WinEvent -ComputerName $DCName -FilterXPath $XPathQuery -LogName $LogName
ForEach ($Event in $Events) {
$EventXML = [xml]$Event.ToXml()
$EventID = $Event.Id
$EventTime = $Event.TimeCreated
if ($EventID -eq $LogonEventID) {
Write-Host "Logon event for user $Username at $EventTime on domain controller $DCName"
} elseif ($EventID -eq $LogoffEventID) {
Write-Host "Logoff event for user $Username at $EventTime on domain controller $DCName"
}
}
} catch {
Write-Warning "Unable to query events on domain controller $DCName. Error: $($_.Exception.Message)"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment