1
votes

I am looking to carry out a bulk removal of members from multiple groups from an imported CSV file of SAMAccountName, ADGroup. I could just loop through every record in the array (of which there will be 1600 entries) but it would be better if I could collate all of the users that are in a particular group and issue the Remove-ADGroupMember with multiple users.

I'm not sure how to process the data in the array so it appears as ADGroup, MultipleSAMAccountNames - I'm probably missing something obvious.

Example CSV:

SAMAccountName, ADGroup
User1, GroupA
User2, GroupA
User3, GroupB
User4, GroupA

Example Code:

Import-Module ActiveDirectory
$Users = Import-CSV "Users.csv"
foreach ($User in $Users)
 {
 Remove-ADGroupMember -identity $User.ADGroup -Members $User.SAMAccountName
 }

Desired:

foreach ($Group in $Users)
     {
    Remove-ADGroupMember -identity $Group.ADGroup -Members $Group.MultipleSAMAccountNames
     }

Thanks in advance

2

2 Answers

0
votes

Try this:

$Users = Import-CSV "Users.csv"
$Groups = $Users.ADGroup | Sort-Object -Unique

foreach ($Group in $Groups) {
    Remove-ADGroupMember -identity $Group -Members ($Users | Where-Object { $_.ADGroup -eq $Group }).SamAccountName
}
  • Gets a unique list of the groups in the CSV.
  • Loops through each unique group and uses Where-Object to filter $Users for any users that match that group, the result of which is then sent to the -Members parameter.

Note this is untested code, so use with care.

0
votes

Mark Wragg beat me to it, but here's my (also untested) solution without the need for a Where-Object clause:

Import-Module ActiveDirectory

# read the CSV file and group the objects by the 'ADGroup' property
$UsersAndGroups = Import-CSV "Users.csv" | Group-Object -Property ADGroup

# loop through the groups
foreach ($group in $UsersAndGroups) {
    # get an array of users belonging to this group
    $accounts = $group.Group | Select-Object -ExpandProperty SAMAccountName -Unique
    # remove them all from the group
    Remove-ADGroupMember -Identity $group.Name -Members $accounts
}

For testing purposes, add the -WhatIf switch at the end of the Remove-ADGroupMember command.