Dave Herrell - Blog - IT Toolbox - PowerShell Banner

PowerShell Basics: Send Slack Alert for Locked Out Users

We went over how to send a Slack alert to a channel already, let’s take it a step further and make it more useful.   In this case, we want to send an alert to our Slack channel when an Active Directory account has been locked out.  

First, you will need a valid Slack webhook with permissions to send into the desired channel. 

Once you’ve created your webhook, then it time to create your PowerShell script.  

Create this script, once complete you want to save it as a .ps1 file so you can use it. 

 

				
					# Webhooks Channel
$SlackChannelUri = "https://hooks.slack.com/services/HELLO/THERE/GETYOUROWNTOKEN"
$ChannelName = "#dave-test"
 
$BodyTemplate = @"
    {
        "channel": "CHANNELNAME",
        "username": "AD Users Locked Out",
        "text": "*DOMAIN_USERNAME* account is currently locked out. \nTime: DATETIME.",
        "icon_emoji":":closed_lock_with_key:"
    }
"@
 
 
if (Search-ADAccount -LockedOut){
    foreach ($user in (Search-ADAccount -LockedOut)){
        $body = $BodyTemplate.Replace("DOMAIN_USERNAME","$user").Replace("DATETIME",$(Get-Date)).Replace("CHANNELNAME","$ChannelName")
        Invoke-RestMethod -uri $SlackChannelUri -Method Post -body $body -ContentType 'application/json'
    }
}

				
			

This will scan your entire Active Directory for any account(s) that are currently locked out.  IF it finds any locked out accounts, it will send the account name to your Slack channel that you set within your script. 

Your alert should fire similar to this:

 

This will state the full OU where you can find the account/name and the time it was locked out. 

You can set this up to run every so many minutes for instance via a Scheduled Task on your Windows Server.   For example, we run this every 5 minutes.  If nothing is found, nothing will be sent into the channel.  

Hope you find this helpful!