Hey everyone! I'm looking for some help with a script for cleaning up user accounts in Active Directory. I work at a small outsourcing company with around 1,000 users, but only about 20-30 log in daily, while many go months without logging in. My boss is concerned about security and wants to disable accounts that haven't been logged into for 90 days. He also wants to move users to an 'archive' organizational unit (OU) after 12 months of inactivity and remove them from all groups while documenting these changes. I'm thinking a PowerShell script might be the way to go for running this process regularly, but what do you all think? Any tips on how to do this efficiently?
3 Answers
It sounds like you’re on the right track with a PowerShell script! Starting with a scheduled task is a good way to automate this. For example, you can use a script similar to this to disable accounts after 90 days of inactivity:
```powershell
$InactivityThreshold = 90
$CurrentDate = Get-Date
$CutoffDate = $CurrentDate.AddDays(-$InactivityThreshold)
$InactiveUsers = Get-ADUser -Filter {LastLogonDate -lt $CutoffDate} -Properties LastLogonDate
foreach ($user in $InactiveUsers) {
Disable-ADAccount -Identity $user.SamAccountName -Confirm:$false
Set-ADUser -Identity $user.SamAccountName -Description "Disabled due to inactivity for $InactivityThreshold days."
}
Write-Host "Finished processing inactive users."
```
This checks for users who haven’t logged in for the specified days and disables their accounts. You’ll also want to ensure that you're not affecting service accounts, so be careful with your filters!
Definitely consider how you will handle accounts that never logged in. Also, for your archiving process, after a year, you could use `Move-ADObject` to shift accounts to the archive OU. You might want to run a separate script for that, just to keep it organized.
Thanks for the suggestion! I hadn’t thought about separating the scripts for different tasks. I’ll definitely keep that in mind to simplify things!
Using `Get-ADUser -Filter {Enabled -eq $true -and LastLogonDate -lt 90}` is a solid method for identifying users to archive or disable. Just be sure to have a backup of any data before making changes!
Great starting point! Just be cautious with accounts that haven't logged in at all—it might disable new users right away. Also, consider filtering out accounts that have special properties like `PasswordNeverExpires` or `UserCannotChangePassword` to avoid issues.