Home > database >  How to remove all users from groups
How to remove all users from groups

Time:01-18

I would like to remove all users from groups. My issue is the fact that I have GroupNames that contain '@' so it fails... any help will be appreciate. Thanks

$groupNames = @"
Groups;
@Test-Group-FIN #fail
@Test-Group-HR  #fail
SupportGAP  #it works for this group
"@ | Convertfrom-csv -Delimiter ";"


#Remove members
foreach ($ADGroup in $groupNames) {
Get-ADGroupMember -Identity $ADGroup.Groups.Trim() | ForEach-Object {Remove-ADGroupMember $ADGroup.Groups.Trim() $_ -Confirm:$False }

 }

CodePudding user response:

please try removing group members using the following method

$groups = @('@Test-Group-FIN','@Test-Group-HR','SupportGAP')
foreach ($group in $groups){
    Get-ADGroup $group | Set-ADGroup -Clear member
}

please note that we are using here the ldap attribute member not members

CodePudding user response:

I was personally unaware AD Groups could have @ in their Name attribute. You can give this a try and see if it does what you expect, if so, you can remove the -WhatIf switch. I have also added a filter for group members where ObjectClass = user so it does not remove other AD Objects.

My recommendation would be to rename these groups having @ in their name, assuming it is possible and is not wrong data from the Csv.

If below code does not find those groups with the @ in their names, you can try replacing the @ with * and perform a wildcard search, over those groups, however it may find more groups than expected.

foreach($group in $groupNames.Groups)
{
    # Uncomment below line and remove the line below it if it
    # does not find those groups
    # $filter = "(name=$($group.Replace('@','*')))"
    $filter = "(name=$group)"
    $adGroup = Get-ADGroup -LDAPFilter $filter
    if(-not $adGroup) {
        Write-Warning "$group could not be found..."
        continue
    }
    $members = Get-ADGroupMember $adGroup | Where-Object ObjectClass -EQ user
    Remove-ADGroupMember -Identity $adGroup -Members $members -WhatIf
}
  •  Tags:  
  • Related