From 803cd36b34a42b5a4e6c8ade3c6e8d6f12822c22 Mon Sep 17 00:00:00 2001 From: Thomas De Reyck Date: Fri, 8 Nov 2024 15:48:50 +0100 Subject: [PATCH] Added a script to automatically disable expired users. --- .../disable_expired_users/start.ps1 | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 microsoft/active_directory/disable_expired_users/start.ps1 diff --git a/microsoft/active_directory/disable_expired_users/start.ps1 b/microsoft/active_directory/disable_expired_users/start.ps1 new file mode 100644 index 0000000..d89bb72 --- /dev/null +++ b/microsoft/active_directory/disable_expired_users/start.ps1 @@ -0,0 +1,24 @@ +# This script searches AD for user accounts with an expiration date in the past. If it finds any, it actually disables them. + +# This is the maximum number of accounts that the script may disable in a single run. A safety measure to prevent accidentally disabling users in bulk. +$MaxActions = 10 + +$LogDir = Join-Path -Path $PSScriptRoot -ChildPath "logs" +New-Item $LogDir -ItemType Directory -ErrorAction SilentlyContinue > $null +$ReportId = Get-Date -Format "yyyyMMdd-HHmmss" + +$Users = Get-ADUser -Filter * -Properties SamAccountName, Enabled, AccountExpirationDate | select SamAccountName, Enabled, AccountExpirationDate + +&{ + ForEach($User in $Users) { + If($User.Enabled -eq $true -and $User.AccountExpirationDate -and ($User.AccountExpirationDate -le (Get-Date))) { + Disable-ADAccount -Identity $User.SamAccountName + "$($User.SamAccountName) has expired on $($User.AccountExpirationDate) and has been disabled." + $MaxActions-- + If($MaxActions -eq 0) { + "Maximum number of actions reached for this run. Quitting..." + Break + } + } + } +} *>&1 | Tee-Object -FilePath (Join-Path -Path $LogDir -ChildPath "log-$ReportId.txt") \ No newline at end of file