You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过PowerShell按组批量移除AD组成员(基于CSV导入)

Optimize Bulk AD Group Member Removal by Grouping Users from 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 group
  • Group: 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 be ADGroup (with leading space). Either edit the CSV to remove the space, or use Import-CSV "Users.csv" -Header "SAMAccountName","ADGroup" to force correct column names.
  • Confirm Prompt: The -Confirm:$false flag skips the "Are you sure?" prompt for each removal. Omit it if you want to verify each action manually.

内容的提问来源于stack exchange,提问作者Johnnie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:35:57