Overview
This article provides a comprehensive guide to using PowerShell for Windows Security event logging. It covers cmdlets, best practices, and real‑world examples.
On this page
Get-EventLog
Retrieves events from event logs on local or remote computers.
Get-EventLog -LogName Security -Newest 20 | Format-Table TimeGenerated, EntryType, Source, EventID, Message -AutoSize
Common parameters:
-LogName: Name of the log (e.g.,System,Application,Security)-Newest: Number of most recent entries to retrieve-After/-Before: Filter by date range
Write-EventLog
Writes an entry to an event log.
Write-EventLog -LogName Application -Source "MyScript" -EventID 3001 -EntryType Information -Message "Script completed successfully."
Ensure the source exists before writing:
If (-not (Get-EventLog -List | Where-Object {$_.Log -eq 'Application' -and $_.Source -contains 'MyScript'})) {
New-EventLog -LogName Application -Source "MyScript"
}
Clear-EventLog
Clears all entries from the specified event log.
Clear-EventLog -LogName Security
Use with caution – clearing the Security log removes audit trails.
Practical Examples
Search for failed login attempts
Get-EventLog -LogName Security -InstanceId 4625 |
Where-Object {$_.Message -match "Account Name"} |
Select-Object TimeGenerated, Message |
Format-Table -AutoSize
Export Security log to CSV
Get-EventLog -LogName Security -After (Get-Date).AddDays(-7) |
Export-Csv -Path "$env:USERPROFILE\Desktop\SecurityLog.csv" -NoTypeInformation
Troubleshooting
- Run PowerShell as Administrator to access the Security log.
- Verify the
EventLogservice is running (Get-Service -Name EventLog). - Check the source registration if
Write-EventLogfails.