If you need to validate inactive users in Active Directory and remove them from specific AD groups using PowerShell, you can follow these steps:
- Identify inactive users
- You can determine inactivity based on the
lastLogonTimestamp
attribute. - Convert it to a readable date and filter users who haven't logged in for a specified period (e.g., 90 days).
- You can determine inactivity based on the
- Validate the list of inactive users
- Export the list to a CSV for review before making any changes.
- Remove inactive users from specific AD groups
- Once validated, remove them from the groups.
Here is a sample script:
# Define variables
$DaysInactive = 90
$DateThreshold = (Get-Date).AddDays(-$DaysInactive)
# Get inactive users
$InactiveUsers = Get-ADUser -Filter {Enabled -eq $true -and lastLogonTimestamp -lt $DateThreshold} -Properties lastLogonTimestamp |
Select-Object SamAccountName, DistinguishedName, @{Name="LastLogon";Expression={[datetime]::FromFileTime($_.lastLogonTimestamp)}}
# Export for validation
$InactiveUsers | Export-Csv -Path "C:\Temp\InactiveUsers.csv" -NoTypeInformation
Write-Host "Inactive user list exported. Review before proceeding."
# Review the CSV before continuing!
Pause
# Define target AD groups to remove users from
$Groups = @("Group1", "Group2", "Group3") # Update with actual group names
# Remove inactive users from groups
foreach ($User in $InactiveUsers) {
foreach ($Group in $Groups) {
Remove-ADGroupMember -Identity $Group -Members $User.SamAccountName -Confirm:$false -ErrorAction SilentlyContinue
Write-Host "Removed $($User.SamAccountName) from $Group"
}
}
Write-Host "Inactive users removed from specified groups."
The script
- Fetches users who haven't logged in for 90 days (adjustable).
- Exports the list to
C:\Temp\InactiveUsers.csv
for validation. - Pauses execution so you can review and confirm.
- Removes inactive users from specified AD groups.
You might need to run this script with Domain Admin privileges. Ensure the Active Directory module is installed (RSAT: Active Directory
on Windows Server).
If the above response helps answer your question, remember to "Accept Answer" so that others in the community facing similar issues can easily find the solution. Your contribution is highly appreciated.
hth
Marcin