Forum Discussion

Louaialobaidi's avatar
Louaialobaidi
Copper Contributor
Oct 05, 2023

powershell script

Hi 

 

I need a powershell script that when AD user account is locked out the admin will get a notification email.

 

 

Thank you

  • somnio0505's avatar
    somnio0505
    Brass Contributor

    Hi, Louaialobaidi

    How about to using 'Task Scheduler" (taskschd.msc).

    New scheduled task

    - Trigger : Event ID 4740

    - Action : Run powershell script (noti.ps1)

     

    eg. noti.ps1 ########################################################################

    $SMTPServer = '1.1.1.1' # Your SMTP Server

    $Subject = 'Account Lock Notification'

    $From = 'noti mail account'

    $To = 'admin mail acount'

    $Time = (get-date -Format yyyy.mm.dd)

    $Body = "Some account locked out at $Time ."

    # If you want to show locked accounts, it might be a good idea to proceed another way.

     

    Send-MailMessage -From $From -To $To -Subject $Subject -Body $Body -SmtpServer $SMTPServer ########################################################################

     

    * Event ID 4740 (https://learn.microsoft.com/en-us/windows/security/threat-protection/auditing/event-4740)

     

    I did not provide a detailed script, but if you have any questions, please feel free to reply.

    • randriksen_'s avatar
      randriksen_
      Brass Contributor

       Louaialobaidi 

       

      As somnio0505 suggests, make a scheduled task triggered on the event

       

      and have it run something like this:

      $alert = Get-EventLog -LogName security -instanceid 4740 -Newest 1
      $body = $alert.message
      
      
      
      #Send email with the report
      $smtpServer = "yourmailserver"
      $smtpPort = 25
      #$smtpUsername = "email address removed for privacy reasons"
      #$smtpPassword = "your_email_password"
                   
      $to = "sendto"
      $from = "sendrom"
      $event = $alert.entrytype
      $time = $alert.TimeGenerated
      $subject = "$event - $time"
                   
      $message = New-Object System.Net.Mail.MailMessage $from, $to
      $message.Subject = $subject
      $message.Body = $body
      #$message.IsBodyHtml = $true
                   
      $smtp = New-Object System.Net.Mail.SmtpClient $smtpServer, $smtpPort
      #$smtp.EnableSsl = $true
      #$smtp.Credentials = New-Object System.Net.NetworkCredential $smtpUsername, $smtpPassword
      
      $smtp.Send($message)
      

      You'll have to adapt it to your email server and environment, but it should work as long as you get the right event code

       

       

      -Ole

Resources