-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemoveBulkUsersFromCsv.ps1
More file actions
61 lines (52 loc) · 3.09 KB
/
RemoveBulkUsersFromCsv.ps1
File metadata and controls
61 lines (52 loc) · 3.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# set false after confirming results
$DryRun = $false
$UsersToRemove = Import-Csv -Path "getSamAccountNames_Data.csv"
# loop through each user and disable their account
foreach ($employee in $UsersToRemove){
try{
$matchedSamNames = $employee.MatchedSamAccountNames
if (-not $matchedSamNames -or $matchedSamNames.Trim() -eq ""){
Write-Host "No matched SamAccountName for $($employee.First_Name) $($employee.Last_Name)." -ForegroundColor DarkYellow
continue
}
$samAccountList = @($matchedSamNames.Split(';') | Where-Object { $_ -ne ''})
if ($samAccountList.Count -eq 1){
# only one user found, can be removed
$samAccount = $samAccountList[0]
$user = Get-ADUser -Identity $samAccount -Properties Enabled -ErrorAction Stop
if ($DryRun) {
if ($user.Enabled -eq $false){
Write-Host "[Dry Run] Found unique user $samAccount. Removing account..." -ForegroundColor Yellow
# deleted remove cmdlet for dry run
Write-Host "Successfully removed user account for $samAccount." -ForegroundColor Green
}
else{
Write-Host "[Dry Run] Would disable and remove active user: $samAccount" -ForegroundColor Cyan
}
} else {
if ($user.Enabled -eq $false){
# if user is disabled then remove account
Write-Host "Found unique user $samAccount. Removing account..." -ForegroundColor Yellow
Remove-ADUser -Identity $samAccount -Confirm:$false -ErrorAction Stop
Write-Host "Successfully removed user account for $samAccount." -ForegroundColor Green
}
else{
# disable and remove account, best practice might be to disable for a couple days
# but for this project we want to remove immediately
Write-Host "Found unique user $samAccount. Disabling and then removing account..." -ForegroundColor Yellow
Disable-ADAccount -Identity $samAccount -ErrorAction Stop
Write-Host "Successfully disabled and removed user account for $samAccount." -ForegroundColor Green
Remove-ADUser -Identity $samAccount -Confirm:$false -ErrorAction Stop
}
}
} elseif ($samAccountList.Count -gt 1) {
# multiple user entries, go through them carefully.
Write-Host "WARNING: Multiple users found for $($employee.First_Name) $($employee.Last_Name). Skipping removal." -ForegroundColor Red
Write-Host "Manual review required for the following accounts: $matchedSamNames" -ForegroundColor Red
} else {
Write-Host "No user found for $($employee.First_Name) $($employee.Last_Name). " -ForegroundColor DarkYellow
}
} catch{
Write-Host "Error processing accounts for $($employee.First_Name) $($employee.Last_Name): $($_.Exception.Message)" -ForegroundColor Red
}
}