In this script, we first define the name of the group we want to remove users from. Then, we use the Import-Csv
cmdlet to read a CSV file that contains a list of user names in a column named “UserName”.
We then loop through each user in the CSV file and try to retrieve the corresponding user object using the Get-ADUser
cmdlet. If the user object is found, we use the Remove-ADGroupMember
cmdlet to remove the user from the group. We also use the -Confirm:$false
parameter to suppress the confirmation prompt.
If the user object is not found, we simply write a message to the console indicating that the user was not found.
Make sure that the CSV file is properly formatted with the user names in a column named “UserName”. Also, make sure that you have the Active Directory module for PowerShell installed on your computer before running this script.
import-module Activedirectory
# Replace "Group Name" with the name of the group you want to remove users from
$group = "Group Name"
$users = Import-Csv -Path "C:\UsersToRemove.csv"
foreach ($user in $users) {
$userName = $user.UserName
$userObject = Get-ADUser -Identity $userName
if ($userObject) {
Remove-ADGroupMember -Identity $group -Members $userObject -Confirm:$false
Write-Host "User '$userName' removed from group '$group'."
}
else {
Write-Host "User '$userName' not found."
}
}