Powershell send email on event id

253 views Asked by At

I found a tutorial to send an email when a certain event occurs. The code is this:

$EventId = 4771
$A = Get-WinEvent -MaxEvents 1 -FilterHashTable @{Logname = "System" ; ID = $EventId}
$Message = $A.Message
$EventID = $A.Id
$MachineName = $A.MachineName
$Source = $A.ProviderName
$EmailFrom = "[email protected]"
$EmailTo = "[email protected]"
$Subject ="Alert From $MachineQ"
$Body = "EventID: $EventIDnSource: $SourcenMachineQ: $MachineQ `nMessage: $Message"
$SMTPServer = "smtp.server"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)

The problem is that I would also like to receive the date/time of the event in the email but I don't know how to add that parameter. Currently the email looks like this:

EventID: 4771
Source: Microsoft-Windows-Security-Auditing
MachineName: server.domain 
Message: user blocked.

I would like something like:

EventID: 4771
Source: Microsoft-Windows-Security-Auditing
**Date: 25/11/2022 10:02**
MachineName: server.domain 
Message: user blocked.

Could someone tell me how to modify the code to add this parameter?

0

There are 0 answers