Script Retrieves and logs Windows logon and logoff events
PowerShell script that retrieves login and logout events from the event logs and exports the information to a CSV file.
The script provided should work for gathering login and logout time information. Here's a breakdown of the script:
- The script starts by defining parameters using the Param block. The script accepts the $Computer parameter (defaulting to "SERVER1") to specify the target computer and the $Days parameter (defaulting to 7) to specify how many days back to look for events.
- The script clears the console with cls.
- An empty array $Result is created to store the extracted event information.
- The script begins gathering event logs using the Get-EventLog cmdlet. It retrieves events from the "System" log with the source "Microsoft-Windows-WinLogon" that occurred after the specified number of days ago on the target computer.
- The script then processes the retrieved event logs using a For Each loop. If the event instance ID matches 7001, it's considered a "Logon" event. If the instance ID is 7002, it's considered a "Logoff" event. If the instance ID doesn't match either, the loop continues to the next event.
- For each processed event, a new PSObject is created to store the event's time, event type (Logon/Logoff), and the user who was involved in the event. The user is translated from the Security Identifier (SID) to the user account name using the SecurityIdentifier and Translate methods.
- The created PSObject is added to the $Result array.
- After processing all events, the $Result array is sorted by time in descending order.
- The sorted result is exported to a CSV file with a filename based on the current date using the Export-CSV cmdlet.
The below scripts
****************************
Param (
[string]$Computer = "Server1",
[int]$Days = 7
)
cls
$Result = @()
Write-Host "Gathering Event Logs, this can take a while..."
$ELogs = Get-EventLog System -Source Microsoft-Windows-WinLogon -After (Get-Date).AddDays(-$Days) -ComputerName $Computer
If ($ELogs) {
Write-Host "Processing..."
foreach ($Log in $ELogs) {
if ($Log.InstanceId -eq 7001) {
$ET = "Logon"
}
elseif ($Log.InstanceId -eq 7002) {
$ET = "Logoff"
}
else {
continue
}
$UserSid = $Log.ReplacementStrings[1]
$User = (New-Object System.Security.Principal.SecurityIdentifier $UserSid).Translate([System.Security.Principal.NTAccount])
$Result += New-Object PSObject -Property @{
Time = $Log.TimeGenerated
'Event Type' = $ET
User = $User.Value
}
}
$Result | Select-Object Time, "Event Type", User | Sort-Object Time -Descending | Export-CSV "D:\Projects\000_Sysadmin\Server_Logs\SERVER1_SERVERLOG_$(Get-Date -Format 'yyyyMMdd').csv" -NoTypeInformation
}