批量移除跨域用户(外部安全主体)从AD组的PowerShell脚本问题
Got it, let's fix your script and get this bulk operation working properly. The key issues with your modified attempt were misusing Get-Content with AD-specific parameters and not properly converting username strings into valid AD user objects. Here's a robust solution:
Corrected PowerShell Script
# Configure your parameters first for easy maintenance $GroupsFilePath = "C:\temp\groups.txt" $UsersFilePath = "C:\temp\users0.txt" $TargetDC = "DC01.domain.com" $DomainSearchBase = "DC=domain,DC=com" # Read the list of groups and usernames from files $Groups = Get-Content $GroupsFilePath $UserNames = Get-Content $UsersFilePath # Loop through each user in the list foreach ($UserName in $UserNames) { try { # Fetch the AD user object (critical - we need this for Remove-ADGroupMember) $User = Get-ADUser -Identity $UserName ` -Server $TargetDC ` -SearchBase $DomainSearchBase ` -ErrorAction Stop Write-Host "`nProcessing user: $($User.SamAccountName)" -ForegroundColor Cyan # Remove the user from each group in the list foreach ($Group in $Groups) { try { Remove-ADGroupMember -Identity $Group ` -Members $User ` -Server $TargetDC ` -Confirm:$false ` -ErrorAction Stop Write-Host "✅ Successfully removed $($User.SamAccountName) from $Group" -ForegroundColor Green } catch { Write-Host "❌ Failed to remove $($User.SamAccountName) from $Group: $_" -ForegroundColor Red } } } catch { Write-Host "`n⚠️ Could not locate user $UserName on $TargetDC: $_" -ForegroundColor Yellow } }
Key Fixes & Explanations
Convert Usernames to AD Objects:
Your original script tried to pass raw username strings fromGet-ContenttoRemove-ADGroupMember, which doesn't work—you need validADUserobjects. We useGet-ADUserwith-Serverto fetch each user from the target DC.Proper Parameter Usage:
Get-Contentis just for reading text files, so adding-Serverto it was invalid.Remove-ADGroupMemberdoesn't use-searchbase; instead, we specify-Serverto ensure we're interacting with the correct domain controller for group operations.
Error Handling:
Addedtry/catchblocks to catch common issues like missing users, non-existent groups, or users not being in a group. This gives you clear feedback instead of silent failures.
Safety Tip Before Running
To test the script without making actual changes, add the -WhatIf parameter to Remove-ADGroupMember. This will show you what would happen without modifying AD:
Remove-ADGroupMember -Identity $Group ` -Members $User ` -Server $TargetDC ` -Confirm:$false ` -WhatIf ` -ErrorAction Stop
内容的提问来源于stack exchange,提问作者Daniel Gower

