Public/Invoke-EventLogs.ps1
function Invoke-GetEventLog { [PoshBot.BotCommand( CommandName = 'events', Aliases = ('event', 'logs', 'eventlog') )] [cmdletbinding()] param( [parameter(Mandatory)] [string]$ComputerName, [parameter()] [int]$HoursBack = 48 ) $AllResults = @() foreach ($Computer in $ComputerName) { $Result = $Null write-output "$(Get-Date) - Working on $Computer - Eventlog" $starttime = (Get-Date).AddHours(-$HoursBack) try { write-output "$(Get-Date) - Trying with Get-WinEvent" $result = Get-WinEvent -ErrorAction stop -ComputerName $Computer -filterh @{LogName = (Get-WinEvent -Computername $Computer -ListLog * | Where-Object { ($_.logtype -eq 'administrative') -and ($_.logisolation -eq 'system') } | Where-Object recordcount).logname; StartTime = $starttime; Level = 1, 2 } | Select-Object machinename, timecreated, providername, logname, id, leveldisplayname, message $result } catch [System.Diagnostics.Eventing.Reader.EventLogException] { switch -regex ($_.Exception.Message) { "RPC" { Write-Warning "$(Get-Date) - RPC error while communicating with $Computer" $Result = 'RPC error' } "Endpoint" { write-output "$(Get-Date) - Trying with Get-EventLog for systems older than Windows 2008" try { $sysevents = Get-EventLog -ComputerName $Computer -LogName system -Newest 1000 -EntryType Error -ErrorAction Stop | Where-Object TimeGenerated -gt $starttime | Select-Object MachineName, @{Name = 'TimeCreated'; Expression = { $_.TimeGenerated } }, @{Name = 'ProviderName'; Expression = { $_.Source } }, LogName, @{Name = 'Id'; Expression = { $_.EventId } }, @{Name = 'LevelDisplayName'; Expression = { $_.EntryType } }, Message if ($sysevents) { $result = $sysevents } else { Write-Warning "$(Get-Date) - No events found on $Computer" $result = 'none' } } catch { $Result = 'error' } } Default { Write-Warning "$(Get-Date) - Error retrieving events from $Computer" } } } catch [Exception] { Write-Warning "$(Get-Date) - No events found on $Computer" $result = 'none' } if (($result -ne 'error') -and ($result -ne 'RPC error') -and ($result -ne 'none')) { write-output "$(Get-Date) - Consolidating events for $Computer" $lastuniqueevents = $null $lastuniqueevents = @() $ids = ($result | Select-Object id -unique).id foreach ($id in $ids) { $machineevents = $result | Where-Object id -eq $id $lastuniqueevents += $machineevents | Sort-Object timecreated -Descending | Select-Object -first 1 $lastuniqueevents | Add-Member -MemberType NoteProperty -Name "NumEvents" -Value ($machineevents | Measure-Object).Count -Force } $AllResults += $lastuniqueevents | Select-Object MachineName, NumEvents, TimeCreated, ProviderName, LogName, Id, LevelDisplayName, Message $AllResults } } # New-PoshBotCardResponse -Type Normal -Text ($pcevents | format-list -property * | Out-String) } |