Situatie
Here’s a PowerShell script to check for inactive users in Active Directory based on a specified number of days and remove them:
Solutie
# Set the number of days threshold for inactive users
$inactiveDays = 90
# Get the current date
$currentDate = Get-Date
# Calculate the threshold date
$thresholdDate = $currentDate.AddDays(-$inactiveDays)
# Get inactive users from Active Directory
$inactiveUsers = Get-ADUser -Filter {LastLogonDate -lt $thresholdDate -and enabled -eq $true} -Properties LastLogonDate
# Remove inactive users
foreach ($user in $inactiveUsers) {
Write-Host “Removing inactive user: $($user.SamAccountName)…” Disable-ADAccount -Identity $user.SamAccountName Write-Host “User $($user.SamAccountName) disabled successfully.” # Optionally, you can remove the user account permanently using Remove-ADUser # Remove-ADUser -Identity $user.SamAccountName -Confirm:$false
}
This script will:
- Set the number of days threshold for inactive users
- Get the current date
- Calculate the threshold date by subtracting the number of inactive days from the current date
- Get inactive users from Active Directory who have not logged in since the threshold date and whose accounts are enabled
- Disable each inactive user account using Disable-ADAccount
- Optionally, you can permanently remove the user account by uncommenting the Remove-ADUser line. However, exercise caution when permanently removing user accounts.
Please ensure that you have the necessary permissions to disable or remove user accounts in Active Directory and thoroughly test the script in a non-production environment before running it in a production environment.
Leave A Comment?