PS script generating single alert for multiple windows event ID

I have created PS script to notify me via email when any account in Active Directory is deleted. I attached script with the relevant EVENT.

Using ADUC (GUI) on the AD server, If I delete single user account, I receive notification BUT if I try to DELETE TWO users at a time by selecting BOTH User accounts, the script sends two alerts for same user , not for each

In event viewer I can see each user Event separately. but What I have noticed that maybe dueto same datetime of events, the get-event is getting last event only. If I delete single user one by one, then alerts works fine for each user.

PS Script:

# Script to get event details & sends email or echo output
###### Modification Starts here
$EventID = "4726"
$From = ""
$To1 = ""
$SmtpServer = "10.0.01"
###### Modification Ends here
$GetEvent = Get-EventLog -LogName "Security" -InstanceID $EventID -Newest 1
$EventTime = $GetEvent.TimeGenerated
$GetEventMessage = $GetEvent.Message
$AccountSid = $($GetEvent.ReplacementStrings[3])
$objSID = New-Object System.Security.Principal.SecurityIdentifier ("$AccountSid")
$Account = $objSID.Translate( [System.Security.Principal.NTAccount])
$messageParametersTo1 = @{
Subject = "$EventID - $env:computername - $Account - Account DELETED"
Body = "EventID: $EventID - $env:computername - $objUser - Account DELETED on $EventTime.`n`nEvent Details:`n`n $GetEventMessage `n`n`n`n`Script Powered by XZY / MYCOMP IS Dept"
From = "$From"
To = "$To1"
SmtpServer = "$SmtpServer"
Send-MailMessage @messageParametersTo1

Hello syed.jahanzaib87,

In your code in line #9 you are getting only one last event (-Newest 1), so if you delete two users you will get 2 notifications but for the same user(last) as they were deleted at the same time.


Hope that helps.

It would appear that if you want notifications for all events that include ones triggered at the same time, you will have to keep track of the time span between the intervals at which you are checking and report back all events in that timespan and forgo limiting your return to just one.

The script is triggered as soon as particular event id created in event viewer. “Task attached to event”

I would really appreciate for line of code if possible as I really have not much idea on PS scripting. Thanks

Are they both listed in a single event?

Just thinking out loud … some thoughts.

Set an Environment Variable of your liking for the user running the script (run sysdm.cpl, advanced, environment variables) to keep track each time the script runs. You can then access that variable from PS using $ENV:Variable. This way, the value is persistent outside the script.

Then in your code, calculate if the event occurred after the last time run.

$GetEvent = Get-EventLog -LogName “Security” -InstanceID $EventID -After ([DateTime]$ENV:Variable)

At the end of the script, store the new date/time.

$ENV:Variable = Get-Date