
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!
Categories
Recent Posts
- PowerShell: How to Add an Alias to Every Users Mailbox and Groups in Microsoft 365
- Slack: Disable Entra ID User using a slash command.
- Slack: Retrieve Entra ID (MS365) User Information with a slash command.
- Jira Cloud: Disabling Entra ID User Accounts via Automation and Microsoft Runbook
- Jira Cloud: Restart an Azure VM using JSM Assets and Automation