Perrypackettracer / Powershell-scripts-to-use-in-an-active-directory

0 stars 0 forks source link

Powershell script to Automate the monitoring of event logs for specific events or error conditions. #16

Open Perrypackettracer opened 8 months ago

Perrypackettracer commented 8 months ago

Below is a PowerShell script that automates the monitoring of event logs for specific events or error conditions. The script checks for critical events in the Windows System log and sends an email alert to administrators when such events are found. Please note that for the email functionality to work, you need to have access to a mail server or use an external service like SendGrid.

# Define the email parameters
$EmailSender = "your-email@example.com"
$EmailRecipient = "admin@example.com"
$SMTPServer = "smtp.yourmailserver.com"
$SMTPPort = 587
$SMTPUsername = "your-email@example.com"
$SMTPPassword = "your-email-password"

# Define the event log parameters
$LogName = "System"
$EventLevel = "Error"  # You can change this to "Warning" or "Information" as needed
$EventID = 1001  # Specify the Event ID(s) you want to monitor

# Get the last 10 critical events from the specified log
$RecentEvents = Get-WinEvent -LogName $LogName -FilterHashtable @{
    Level = $EventLevel
    ID = $EventID
} -MaxEvents 10 | Select-Object TimeCreated, Id, Message

# Check if critical events are found
if ($RecentEvents) {
    # Prepare the email subject and body
    $EmailSubject = "Critical Events Detected in $LogName Log"
    $EmailBody = "Critical events detected in the $LogName log:`n`n"
    $EmailBody += $RecentEvents | Format-Table -AutoSize | Out-String

    # Send email alert
    Send-MailMessage -From $EmailSender -To $EmailRecipient -Subject $EmailSubject -Body $EmailBody `
        -SmtpServer $SMTPServer -Port $SMTPPort -UseSsl -Credential (New-Object PSCredential $SMTPUsername, (ConvertTo-SecureString $SMTPPassword -AsPlainText -Force))

    Write-Host "Email alert sent to $EmailRecipient."
} else {
    Write-Host "No critical events found in $LogName log."
}

Explanation:

  1. Replace the placeholder values in the email parameters section with your actual email configuration (sender, recipient, SMTP server, port, username, and password).

  2. Modify the event log parameters according to your requirements. The script checks the last 10 events with the specified Event ID(s) and severity level in the specified log.

  3. The script sends an email alert if critical events are found, including details about the events.

  4. The Send-MailMessage cmdlet is used for sending emails. Ensure that you have the necessary permissions and access to the SMTP server.

  5. Customize the script based on your specific event monitoring criteria and execute it periodically, for example, using Task Scheduler, to automate the monitoring of event logs and alert administrators when critical events occur.