Removing Users from all AD Groups based on CSV File

2.5k views Asked by At

Hi I am new to PowerShell, I have a CSV file of Active directory user names, I need to remove them from all their group memberships except the default "Domain Users"

I have this script but it doesn't work, and wondering if any one could advise me on what I am doing wrong.

Import-Module ActiveDirectory

$users = import-csv C:\temp\AD\groups_test.csv

Get-ADPrincipalGroupMembership $user| foreach {Remove-ADGroupMember $_ -Members $user -Identity 
Confirm:$false}
1

There are 1 answers

1
Mathias R. Jessen On

Assuming your CSV has a column SAMAccountName with the user's username, do this:

$users = Import-Csv C:\temp\AD\groups_test.csv

foreach($user in $users){
  Get-ADPrincipalGroupMembership $user.SAMAccountName |Remove-ADGroupMember -Members $user.SAMAccountName -Confirm:$false
}

PowerShell will automatically bind the ADGroup objects output by Get-ADPrincipalGroupMembership to Remove-ADGroupMember's -Identity parameter.