Ad clean-up
Jump to navigation
Jump to search
Cleanup of AD
Create users file account line-by-line
notepad users.txt and paste SAMAccountNames
Disable
disable-users-txt.ps1
Import-Module ActiveDirectory $textFilePath = "users.txt" $usernames = Get-Content -Path $textFilePath | ForEach-Object { $_.Trim() } foreach ($username in $usernames) { if (-not [string]::IsNullOrWhiteSpace($username)) { try { $user = Get-ADUser -Identity $username -Properties Enabled -ErrorAction Stop if ($user.Enabled -eq $false) { Write-Output "Account already disabled: $username" } else { Write-Output "Disabling account: $username" Start-Sleep -Milliseconds 500 Disable-ADAccount -Identity $username -ErrorAction Stop Write-Output "Successfully disabled account: $username" } } catch { Write-Output "E: Failed to disable account: $username. Error: $_" } } }
Delete
delete-users-txt.ps1
$textFilePath = "users.txt" $usernames = Get-Content -Path $textFilePath | ForEach-Object { $_.Trim() } foreach ($username in $usernames) { if (-not [string]::IsNullOrWhiteSpace($username)) { try { $user = Get-ADUser -Identity $username -Properties Enabled, MemberOf -ErrorAction Stop if ($user.Enabled -eq $true) { Write-Output "E: Username $username must be disabled before deletion. Skipping." continue } $groups = $user.MemberOf if ($groups -is [System.Collections.IEnumerable] -and $groups.Count -ge 1) { foreach ($group in $groups) { Write-Output "Removing user $username from group $group." Remove-ADGroupMember -Identity $group -Members $user -Confirm:$false } } Remove-ADUser -Identity $username -Confirm:$false Write-Output "User $username has been removed from all groups and deleted from AD." } catch { Write-Output "E: Failed to delete account: $username. Error: $_" } } }