PowerShell Script for Monitoring User Logon Events

In this post, we will create a PowerShell script that monitors user logon events on a Windows system. This script is useful for security professionals looking to track who is accessing their systems and when. It will utilize the Get-WinEvent cmdlet to fetch logon-related events from the Windows Event Log.
### Step 1: Define the Event Log Parameters
First, we will define the parameters for the event log we want to monitor. We will specify the event ID associated with successful logons and the log name.

$logName = 'Security'
$eventId = 4624

### Step 2: Fetch Logon Events
Next, we will use the Get-WinEvent cmdlet to retrieve the logon events from the Security log. We will filter the events based on the specified event ID.

$logonEvents = Get-WinEvent -LogName $logName -Id $eventId | Select-Object TimeCreated, Message

### Step 3: Display the Logon Events
Now, we will display the retrieved logon events in a readable format. This will show the time of creation and the message associated with each event.

$logonEvents | ForEach-Object {
    Write-Host "Logon Time: $($_.TimeCreated) - Event Message: $($_.Message)"
}

### Step 4: Optional Filtering by User
If you want to filter the logon events by a specific user, you can modify the script to include a user name input. This will allow you to track logon events related to that user.

$userName = 'UserAccount' # Replace with the desired user account
$filteredEvents = $logonEvents | Where-Object { $_.Message -like "*$userName*" }
$filteredEvents | ForEach-Object {
    Write-Host "Filtered Logon Time: $($_.TimeCreated) - Event Message: $($_.Message)"
}

### Conclusion
With this PowerShell script, you can efficiently monitor user logon events on your Windows systems to enhance your security posture. Adjust the user name in the script to track specific accounts as needed.