Remove target group members via powershell
Todays code is useful for removing a large amount of users from one or many targeted groups. This script was created in response to multiple users being added to AD groups by accident – it proved an efficient means to remove the incorrect members quickly and without manual intervention.
Also of note is the use of a Hash object to perform fast array comparison. We’ve used this trick many times for easy object comparison and it proves really useful when you want to quickly determine if a value is contained within an array.
Import-Module ActiveDirectory
# Import our target usernames
$colUsers = get-content userList.txt
# Create a hash object
$userHash = @{}
# This loop populates our hash object with the target usernames
Foreach ($objUser in $colUsers){
# Inject each user into the hash object
$userHash.add("$objUser","")
}
# Grab our target groups - this could also source from a text file
$colGroups = "Target_Group1","Target_Group2"
# Loop through the groups!
Foreach ($objGroup in $colGroups) {
# For each group, we need to capture the membership - we only need the SamAccountName
$colMembers = get-adgroupmember $objGroup | select -Expand SamAccountName
# Then we want to cycle through each member of the current group
foreach ($objMember in $colMembers) {
# Here we are checking if the current member of the target group is contained within our hash object
# If the user is within our hash object, then its a target user!
if ($userHash.contains($objMember)) {
# Remove the target user from the target group and output to the console!
Remove-ADGroupMember -Identity $objGroup -Members $objMember -Confirm:$false
write-host "Removed $objMember from $objGroup"
}
}
}
And there you have it – a simple scripted method to remove target group members from groups.
