Microsoft provides us with the PowerShell module for ActiveDirectory, but it needs to be supported by installing RSAT(Remote Server Administration Tools).
The following is based on AD's PS module to achieve batch deletion of AD user function, read the first column(user name) of Excel, and then call the Remove-ADUser function to delete, it is so simple.
Of course, if you want to read from other columns or the second row, then you need to slightly modify the code.
About AD's PS module: https://learn.microsoft.com/en-us/powershell/module/activedirectory
#########################################################
##
## Read the username in the first column and delete the user from AD
##
## FileName: RemoveAdUsersWithExcel.ps1
## Usage: RemoveAdUsersWithExcel.ps1 "D:\path\to\file.xlsx"
##
## Author: Allen Cai
## Created: 2024-10-16
##
#########################################################
Import-Module ActiveDirectory
Function RemoveAdUsers ($File) {
# Create an Excel object
$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = $false
$Excel.DisplayAlerts = $false
# Open the workbook
$wb = $Excel.Workbooks.Open($File)
# Check if the workbook has any sheets
if ($wb.Sheets.Count -le 0) {
Write-Host "No sheets found in the workbook"
$Excel.Quit()
exit
}
# Get the first sheet
$ws = $wb.Sheets.Item(1)
# Loop through the rows in the sheet
foreach ($row in 1..$ws.UsedRange.Rows.Count) {
# Get the username from the first column
$userName = $ws.Cells.Item($row, 1).Value2
# Check if the username is not null
if ($null -ne $userName) {
try {
Write-Host "Deleting user: $userName"
# Remove the user from AD
$result = Remove-ADUser -Identity $userName
# Check if the user was deleted successfully
if ($result) {
Write-Host "User $userName deleted" -ForegroundColor Green
} else {
Write-Host "Failed to delete user: $userName" -ForegroundColor Yellow
}
}
catch {
Write-Host "Failed to delete user: $userName. Error: $_" -ForegroundColor Red
}
}
}
# Close the excel workbook
$Excel.Quit()
exit
}
# Check if a file path was provided as an argument
if ($args.Length -eq 0) {
Write-Host "Please provide a file path as an argument"
} else {
# Check if the file or directory exists
if (-not (Test-Path $args[0])) {
Write-Host "File or directory does not exist"
exit
}
# Call the function to convert the Excel file to CSV
$file = Get-Item $args[0]
RemoveAdUsers $file
}