Discord alerts for Active Directory Lockouts
This article is about PowerShell and the tasks I use it for.
Would your team appreciate an alert when someone gets locked out of Active Directory? I decided mine did. I scheduled this task to run at Startup and it constantly monitors lockouts and alerts us when it finds one.
<#
20220306 Created by B.M.C. webmaster@phantomcode.org:
I want something that will send an alert when users are locked out of Active Directory
20230505 Modified by B.M.C.:
Changed the logging style, and added a change to keep log modification time current.
#>
Write-Output "Starting Log Management"
#LOG MANAGEMENT
. C:\belfry\managelogs.ps1 $MyInvocation.MyCommand.Name
#End LOG MANAGEMENT
$uriDiscord = "https://discord.com/api/webhooks/XXXXXXXXXXXXXXXXXX/XXXXXXXXXXXXXXXXXXXXXXXXXXX_XXXXXXXXXXXXXXXXXXXX_XXXXXXXXXXXXXXXXXXX" #Alerts
#Launch confirmation
$Body = "$(Get-Date) Active Directory Lockout Monitor started on $($env:computername)"
$payload = [PSCustomObject]@{
content = $Body
}
try {
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 #Not necessary on Windows 10, but necessary on some servers.
Invoke-RestMethod -uri $uriDiscord -Method Post -body ($payload|ConvertTo-Json) -ContentType 'Application/Json' | Out-Null
}catch{
Write-Error (Get-Date) ": Update to webhook went wrong..."
}
[System.Collections.ArrayList]$lockedoutnow=@()
[System.Collections.ArrayList]$lockedoutbefore=@()
While ($true){
Search-ADAccount -LockedOut|%{
[void]$lockedoutnow.Add($_.UserPrincipalName)
"$(Get-Date) Added $($_.UserPrincipalName) to current list"
}
<#if ($lockedoutnow -ne $lockedoutbefore){
Write-Output "Locked out now: $lockedoutnow"
}Else{
Write-Output "No change"
}#>
$foundit=$false
$lockedoutnow|%{
$thisentry=$_
$lockedoutbefore|%{
if ($thisentry -eq $_){$foundit=$true;"$(Get-Date) Found $_ already in the list"}
}
if ($foundit -ne $true){
"$(Get-Date) Send an alert for $_"
$Body = "$_ is now locked out of Active Directory ($($env:computername) monitoring)"
$payload = [PSCustomObject]@{
content = $Body
}
try {
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Invoke-RestMethod -uri $uriDiscord -Method Post -body ($payload|ConvertTo-Json) -ContentType 'Application/Json' | Out-Null
}catch{
Write-Error (Get-Date) ": Update to webhook went wrong..."
}
}
}
$lockedoutbefore=$lockedoutnow
[System.Collections.ArrayList]$lockedoutnow=@()
Start-Sleep -Seconds 3
(Get-Item "$logdir\$logname").LastWriteTime=(Get-Date) #Make sure the modification time on the log gets updated.
}