如何通过PowerShell按组批量移除AD组成员(基于CSV导入)
Hey there, I totally get where you're coming from—running 1600 separate Remove-ADGroupMember calls is inefficient and slow. Grouping users by their target AD group first is the perfect way to cut down on redundant AD module calls and speed up the whole process. Here's how to pull it off:
Core Idea
Use PowerShell's Group-Object cmdlet to aggregate your CSV data by the ADGroup field. This will bundle all users belonging to the same group into a single collection, so you can process each group just once.
Step-by-Step Solution
First, let's adjust your script to group the CSV data properly:
Import-Module ActiveDirectory # Import the CSV (note: if your CSV's ADGroup column has leading space, fix the header first or use -Header to rename) $Users = Import-CSV "Users.csv" # Group the user entries by ADGroup $groupedUsers = $Users | Group-Object -Property ADGroup
Now, $groupedUsers contains a collection of group objects. Each object has:
Name: The name of the AD groupGroup: A sub-collection of all user entries tied to that group
Next, loop through each grouped set and remove all users from the AD group in one go:
foreach ($group in $groupedUsers) { # Extract all SAMAccountNames for the current group $targetUsers = $group.Group | Select-Object -ExpandProperty SAMAccountName # Bulk remove the users - add -Confirm:$false to skip interactive prompts Remove-ADGroupMember -Identity $group.Name -Members $targetUsers -Confirm:$false }
Bonus: Add Error Handling
To make the script more robust, wrap the removal in a Try/Catch block to catch and report any failures:
foreach ($group in $groupedUsers) { $targetUsers = $group.Group | Select-Object -ExpandProperty SAMAccountName try { Remove-ADGroupMember -Identity $group.Name -Members $targetUsers -Confirm:$false -ErrorAction Stop Write-Host "✅ Successfully removed users from group: $($group.Name)" } catch { Write-Error "❌ Failed to process group $($group.Name): $_" } }
Key Notes
- Efficiency Gain: Instead of 1600 individual AD calls, you'll only make one call per unique AD group in your CSV—huge time saver!
- CSV Header Fix: If your original CSV has a space after the comma (like
SAMAccountName, ADGroup), the imported column name will beADGroup(with leading space). Either edit the CSV to remove the space, or useImport-CSV "Users.csv" -Header "SAMAccountName","ADGroup"to force correct column names. - Confirm Prompt: The
-Confirm:$falseflag skips the "Are you sure?" prompt for each removal. Omit it if you want to verify each action manually.
内容的提问来源于stack exchange,提问作者Johnnie

