Skip to content

Instantly share code, notes, and snippets.

@duncansmart
Created July 13, 2017 08:25
Show Gist options
  • Save duncansmart/6bef0b6758feea14fe1f60541b4eb325 to your computer and use it in GitHub Desktop.
Save duncansmart/6bef0b6758feea14fe1f60541b4eb325 to your computer and use it in GitHub Desktop.
Emails filtered eventlogs from previous 24 hours
# powershell.exe -NonInteractive -NoProfile -ExecutionPolicy Unrestricted -Command "& { .\MailEventLogs.ps1 }"
$mailTo = "foo@example.com"
$mailFrom = "$env:COMPUTERNAME@example.com"
$smtpServer = "aspmx.l.google.com"
Set-StrictMode -Version Latest
$startDate = (Get-Date).AddDays(-1).AddMinutes(-5)
$ignore = @{
'Schannel' = 36888, 36887, 36874;
'TermDD' = 50;
'MSSQL$SQLEXPRESS' = 18456, 17806, 18452;
'Microsoft-Windows-Security-Auditing' = 4625;
'Software Protection Platform Service' = 902, 903;
'Microsoft-Windows-User Profiles Service' = -1;
'New Relic .NET Profiler' = 256, 257;
'ASP.NET *' = 1309;
'.NET Runtime' = 1022; # "Loading profiler failed" fails for SQL Server localdb
'Microsoft-Windows-HttpEvent' = 15300, 15301; # "SSL Certificate Settings created/deleted for Port"
}
$log =
"Application","System","Security" | foreach {
$logname = $_
$entries = Get-WinEvent -FilterHashtable @{LogName=$logname; StartTime=$startDate; Level=2,3} -ErrorAction silentlycontinue | where {
$eventsource = $_.ProviderName
$eventids = $ignore.GetEnumerator() | where { $eventsource -like $_.Name } | foreach { $_.Value }
-not ($eventids -contains $_.Id -or $eventids -eq -1)
}
if ($entries) {
"`n## $($logname) ##`n"
$entries | foreach {
$message = $_.FormatDescription()
if ($message -eq $NULL) {
$message = [string]::Join("`r`n", ( $_.Properties | foreach {$_.Value}) )
}
" $($_.TimeCreated.ToString('yyyy-MM-dd HH:mm:ss')) $($_.ProviderName.Trim()) $($_.UserId) [$($_.LevelDisplayName)] $($_.Id): $message `r`n-----------------------"
}
}
}
if ($log) {
$body = ($log | Out-String)
if ($body.Length -gt 100000) { # 100K
$attachment = "$env:TEMP\EventLog.txt"
$body | Out-File $attachment -Encoding "UTF8"
$body = "See attached..."
"Sending message as attachment"
Send-MailMessage -To $mailTo `
-From $mailFrom `
-Subject "EventLog: $env:COMPUTERNAME" `
-SmtpServer $smtpServer `
-Body $body -Attachments $attachment
}
else {
"Sending message"
Send-MailMessage -To $mailTo `
-From $mailFrom `
-Subject "EventLog: $env:COMPUTERNAME" `
-SmtpServer $smtpServer `
-Body $body
}
}
else {
"Nothing to do"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment