How to remove inactive users in Active Directory via powershell

Configurare noua (How To)

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:

  1. Set the number of days threshold for inactive users
  2. Get the current date
  3. Calculate the threshold date by subtracting the number of inactive days from the current date
  4. Get inactive users from Active Directory who have not logged in since the threshold date and whose accounts are enabled
  5. Disable each inactive user account using Disable-ADAccount
  6. 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.

Tip solutie

Permanent

Voteaza

(3 din 7 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?