question

CarlBurch-7484 avatar image
0 Votes"
CarlBurch-7484 asked IanXue-MSFT answered

Get event error in batch file

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
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

IanXue-MSFT avatar image
0 Votes"
IanXue-MSFT answered

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://docs.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.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.