We have one of our very long standing clients wanting to know why some things are being done on a particular server at about 5:30 AM most mornings.

We looked through backup schedules, scheduled tasks, and SQL maintenance plans and other things and couldn’t find anything particularly useful.

We also knew that a few of their users were early risers and this particular server was licensed to have more than 20 concurrent users on at a time, so we decided to produce the script below. It provides a list of all users who either signed in or reconnected to a disconnected session, between 4:00 AM and 9:00 AM.

From that the client was able to determine a very small list of users who were likely causing the issue. They simply asked each one of them what they were doing and then easily figured out what was going on just by talking to them.

You can go through your event logs Applications and Services Logs > Microsoft > Windows > TerminalServices-LocalSessionManager > Operational. looking for events #21 and #24 or you can simply look at the script below and make the changes you want. For instance, you could change the time from 4:00 AM to 9:00 AM, to be 1 AM to 11:00 PM or anything else.


# Which event log and event IDs to look for
$eventLogName = "Microsoft-Windows-TerminalServices-LocalSessionManager/Operational"
$eventIDs = @(21, 24)  # Event ID 21: Logon, Event ID 24: Reconnect

# Create a folder if it doesn't exist
$csvPath = "C:\temp\logins.csv"
if (!(Test-Path -Path "C:\temp")) {
    New-Item -ItemType Directory -Path "C:\temp" | Out-Null
}

# Look for specified IDs 21 & 24
$events = Get-WinEvent -FilterHashtable @{
    LogName = $eventLogName
    ID = $eventIDs
}

# Process and filter results for logins between 4 AM and 9 AM daily
$results = $events | Where-Object {
    $_.TimeCreated.Hour -ge 4 -and $_.TimeCreated.Hour -lt 9
} | ForEach-Object {
    # Determine event type
    $eventType = if ($_.Id -eq 21) { "Logon" } elseif ($_.Id -eq 24) { "Reconnect" } else { "Unknown" }

    # Extract the username and other details
    [PSCustomObject]@{
        UserName = $_.Properties[0].Value   # User's name is typically in the first property
        DateTime = $_.TimeCreated           # Event timestamp
        EventType = $eventType              # Logon or Reconnect
    }
}

# Export to CSV
if ($results) {
    $results | Sort-Object DateTime | Export-Csv -Path $csvPath -NoTypeInformation -Force
    Write-Host "Logins exported successfully to $csvPath"
} else {
    Write-Host "No matching events found between 4 AM and 9 AM."
}


0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *