Created
February 15, 2025 10:25
-
-
Save filipnet/92181f4035c54168cbe5b5b34daa9af8 to your computer and use it in GitHub Desktop.
Retrieves logon (7001) and logoff (7002) events from the system event log of a local or remote computer Displays the results in a formatted table Allows filtering based on a specified time period (default: 10 days)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <# | |
| .SYNOPSIS | |
| Retrieves logon and logoff events from a local or remote computer. | |
| .DESCRIPTION | |
| This script queries the Windows Event Log for logon (7001) and logoff (7002) events. | |
| The results are sorted in descending order by date and displayed in a table. | |
| .PARAMETER Computer | |
| The target computer name (Default: Local computer). | |
| .PARAMETER Days | |
| The number of days to retrieve events for (Default: 10 days). | |
| .EXAMPLE | |
| .\Get-LogonHistory.ps1 -Computer "PC123" -Days 7 | |
| Retrieves logon/logoff events for the last 7 days from computer "PC123". | |
| .NOTES | |
| - Requires administrative privileges on the target computer. | |
| - If "Network path not found" error occurs, enable the Remote Registry service. | |
| - Event ID 7001: Logon, Event ID 7002: Logoff. | |
| #> | |
| param ( | |
| [string]$Computer = $env:COMPUTERNAME, | |
| [int]$Days = 10 | |
| ) | |
| cls | |
| $Result = @() | |
| Write-Host "Gathering event logs, please wait..." | |
| try { | |
| $ELogs = Get-EventLog System -Source Microsoft-Windows-WinLogon -After (Get-Date).AddDays(-$Days) -ComputerName $Computer -ErrorAction Stop | |
| if ($ELogs) { | |
| Write-Host "Processing data..." | |
| foreach ($Log in $ELogs) { | |
| $ET = switch ($Log.InstanceId) { | |
| 7001 { "Logon" } | |
| 7002 { "Logoff" } | |
| default { continue } | |
| } | |
| $Result += [PSCustomObject]@{ | |
| Time = $Log.TimeWritten | |
| 'Event Type' = $ET | |
| User = (New-Object System.Security.Principal.SecurityIdentifier $Log.ReplacementStrings[1]).Translate([System.Security.Principal.NTAccount]) | |
| } | |
| } | |
| $Result | Sort-Object Time -Descending | Format-Table -AutoSize | |
| Write-Host "Done." | |
| } else { | |
| Write-Host "No relevant events found." | |
| } | |
| } | |
| catch { | |
| Write-Host "Error retrieving logs from $Computer." | |
| Write-Host "If you see a 'Network path not found' error, try enabling the Remote Registry service on that computer." | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment