Last active
February 11, 2024 21:28
-
-
Save davidlu1001/563c4e2ef506df7b47f0a42e92d278d4 to your computer and use it in GitHub Desktop.
Get EventLogMessage For Input Source
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
| function Get-EventLogData { | |
| param( | |
| [Parameter(Mandatory = $true)] | |
| [string[]]$Servers, | |
| [Parameter(Mandatory = $true)] | |
| [string[]]$LogNames, | |
| [Parameter(Mandatory = $true)] | |
| [string[]]$ProviderNames, | |
| [int]$DaysAgo = 30 | |
| ) | |
| $EndDate = (Get-Date) | |
| $StartDate = $EndDate.AddDays(-$DaysAgo) | |
| $results = @() | |
| foreach ($Server in $Servers) { | |
| foreach ($LogName in $LogNames) { | |
| foreach ($ProviderName in $ProviderNames) { | |
| Write-Host "Querying $LogName on $Server for provider $ProviderName starting from $StartDate to $EndDate" | |
| try { | |
| $events = Get-WinEvent -ComputerName $Server -FilterHashtable @{ | |
| LogName = $LogName | |
| StartTime = $StartDate | |
| ProviderName = $ProviderName | |
| } -ErrorAction Stop | Where-Object { | |
| $_.TimeCreated -ge $StartDate | |
| } | Sort-Object TimeCreated | |
| $groupedEvents = $events | Group-Object LevelDisplayName | |
| foreach ($group in $groupedEvents) { | |
| $logType = $group.Name | |
| $logEvents = $group.Group | |
| $logMsgCount = $logEvents.Count | |
| $latestLog = $logEvents | Sort-Object TimeCreated -Descending | Select-Object -First 1 | |
| if ($logMsgCount -gt 0) { | |
| $results += [PSCustomObject]@{ | |
| Server = $Server | |
| LogName = $LogName | |
| ProviderName = $ProviderName | |
| LogType = $logType | |
| LogMsgCount = $logMsgCount | |
| LogMessage = $latestLog.Message -replace "`r","" -replace "`n","" | |
| LogTime = $latestLog.TimeCreated | |
| } | |
| } | |
| } | |
| } catch { | |
| Write-Warning "Failed to query $LogName for provider $ProviderName on $Server. Error: $_" | |
| } | |
| } | |
| } | |
| } | |
| return $results | |
| } | |
| # Modify the script to read ProviderNames from an input file | |
| $ProviderNames = Get-Content "path\to\providerNames.txt" | |
| # Example usage | |
| $Servers = @("localhost") | |
| $LogNames = @("Application") | |
| $DaysAgo = 1 | |
| $results = Get-EventLogData -Servers $Servers -LogNames $LogNames -ProviderNames $ProviderNames -DaysAgo $DaysAgo | |
| $results | Export-Csv -Path "./EventLogReport.csv" -NoTypeInformation | |
| Write-Host "Event log data exported successfully." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment