24 lines
1.2 KiB
PowerShell
24 lines
1.2 KiB
PowerShell
# 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") |