Active Directory – remove users from a group

active-directory

I'm looking for a way to remove ALL users from a list of Active Directory groups.

For example I have a txt file with a bunch of group names, and I'd like to go through all of them and remove all the users inside of them.

A way to do it without using a text file would work as well, but I have a very large amount of groups that need to have this done, and might need to in the future as well ( possibly periodically ).

This is what I'm working with now :

Set objGroup = GetObject("LDAP://CN=Finance Users,OU=Finance,DC=fabrikam,DC=com") 

For Each strUser in objGroup.Member 
    objGroup.PutEx ADS_PROPERTY_DELETE, "member", Array(strUser) 
    objGroup.SetInfo 
End 

Thanks!

Best Answer

Powershell. Put all your groups into ingroups.txt, one per line. Save script as .ps1 file, and then execute.

function removeAllUsersFromGroup{
    Param([String]$GroupName)
    BEGIN   { Import-Module ActiveDirectory; if ($GroupName -eq ""){ throw "No group name specified" } Write-Host "Removing users from $GroupName" -f green }
    PROCESS { 
        $groupSID = (Get-ADGroup "Test Group").SID
        $groupMembers = Get-ADGroupMember -Identity $groupSID

        foreach ($member in $groupMembers){
            Remove-ADGroupMember -Identity $groupSID -Member $member.SID
        }
    }
    END     {  }
}

Get-Content .\ingroups.txt | %{ removeAllUsersFromGroup-groupname $_}

You must have the Windows RSAT installed, as it uses the Active Directory cmdlets. If a group does not exist, or is empty, you will get some powershell errors.