Get event error in batch file

Carl Burch 216 Reputation points
2021-03-29T04:57:00.283+00:00

Server 2019 setup.
I presently have a task in task scheduler set up to send an e-mail "on event", with any one of multiple events as a trigger. Specifically, it sends an e-mail on any event that indicates a possible hard drive problem that can/will lead to failure. For example, if event ID 52 (Hard Drive Failure Imminent) is generated in the event log, this will run the task and send the admin an email. The task itself is a powershell script that sends the actual e-mail.
Is there a way in the script that I can "capture" the event ID that triggered the task and include it in the e-mail? I'm thinking there must be some common variable that I can insert, like %errorlevel% for example. The part of the script that generates and sends the email is this:
$EmailTo = "myemail@address.com"
$EmailFrom = "myemail@address.com"
$Subject = "Hard Drive Failure May Be Imminent!"
$Body = "The system has detected a hard drive failure may be imminent.."
$SMTPServer = "smtp.server.net"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("myemail@address.com", "password");
$SMTPClient.Send($SMTPMessage)

Thanks for any assistance you can provide.

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,345 questions
0 comments No comments
{count} votes

Accepted answer
  1. Ian Xue (Shanghai Wicresoft Co., Ltd.) 29,386 Reputation points Microsoft Vendor
    2021-03-30T08:19:59.65+00:00

    Hi,

    The events that trigger the scheduled task are logged in the event logs, not in environment variables. You can query for the events using the Get-WinEvent cmdlet.
    https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.diagnostics/get-winevent

    Best Regards,
    Ian Xue

    ============================================

    If the Answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful