Created
February 16, 2024 11:06
-
-
Save brovish/8bd1e22641f3002ac7e72c85a6a56233 to your computer and use it in GitHub Desktop.
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
| # Define variables | |
| $searchString = "Error" # The string to search for in event logs | |
| $since = (Get-Date).AddDays(-1) # Only events from the last day | |
| $outputFile = "C:\Path\To\Your\events.csv" # Specify your output file path | |
| # Prepare the CSV file | |
| if (Test-Path $outputFile) { | |
| Remove-Item $outputFile -Force # Delete existing file if it exists | |
| } | |
| # Headers for the CSV file | |
| "LogName,TimeCreated,Message" | Out-File $outputFile -Encoding UTF8 | |
| # Retrieve a list of all logs with more than 0 records | |
| $logList = Get-WinEvent -ListLog * | Where-Object { $_.RecordCount -gt 0 } | Select-Object -ExpandProperty LogName | |
| # Iterate through each log | |
| foreach ($logName in $logList) { | |
| # Attempt to retrieve events from each log | |
| try { | |
| Get-WinEvent -LogName $logName -ErrorAction Stop | | |
| Where-Object { $_.TimeCreated -gt $since -and $_.Message -match $searchString } | | |
| ForEach-Object { | |
| # Create an object with event information | |
| $eventInfo = New-Object PSObject -Property @{ | |
| LogName = $logName | |
| TimeCreated = $_.TimeCreated | |
| Message = $_.Message -replace "`r`n", " " # Remove new lines from messages for correct CSV formatting | |
| } | |
| # Append event information to the CSV file | |
| $eventInfo | Select-Object LogName, TimeCreated, Message | Export-Csv -Path $outputFile -NoTypeInformation -Append -Encoding UTF8 | |
| } | |
| } catch { | |
| # Skip the log if events cannot be retrieved | |
| Write-Output "Could not retrieve events from $logName. Skipping..." | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment