Script to remove a group of users from AD Group

Welcome Forums General PowerShell Q&A Script to remove a group of users from AD Group

This topic contains 8 replies, has 5 voices, and was last updated by

 
Participant
3 weeks, 2 days ago.

  • Author
    Posts
  • #125355

    Participant
    Points: 32
    Rank: Member

    Dears,

    Is there anyway to remove users from all AD groups except Domain Users, after export the group membership information to a text file ?

     

    Thanks

    Rajesh

  • #125361

    Moderator
    Points: 175
    Team MemberHelping Hand
    Rank: Participant

    Something like this should work. Not tested, make sure you try in test environment first.

    $users = 'smith01', 'miller01'
    
    foreach ($user in $users) {
        $groups = (Get-ADUser $user -Properties MemberOf).MemberOf 
        Add-Content -Path C:\TEMP\$user.txt -Value $groups
        foreach ($group in $groups) {
            Remove-ADGroupMember $group -member $user -WhatIf
        }
    }
    
  • #125364

    Moderator
    Points: 175
    Team MemberHelping Hand
    Rank: Participant

    I should have pointed out that Domain Users will not be listed in the MemberOf collection.

    • #125366

      Participant
      Points: 32
      Rank: Member

      Thanks a lot. The script created the text outputs with Groups information however users were not removed from the groups.

    • #125369

      Participant
      Points: 288
      Helping Hand
      Rank: Contributor

      Remove the -WhatIf switch from Remove-AdGroupMember. Should work after that.

  • #125370

    Participant
    Points: 895
    Helping Hand
    Rank: Major Contributor

    You have to remove -Whatif. If you don't know what is whatif, please read it here

    https://blogs.technet.microsoft.com/heyscriptingguy/2011/11/21/make-a-simple-change-to-powershell-to-prevent-accidents/

  • #125385

    Participant
    Points: 7
    Rank: Member

    Hi Rajesh,

    You can try below script which i use daily

    
    $users = Get-Content c:\users.txt
    
    foreach ($u in $users){
    
    $u
    
    $User = [ADSI]"LDAP://$u"
    
    ForEach ($GroupDN In $User.memberOf){
    
    $Group = [ADSI]("LDAP://" + $GroupDN)
    
    $Group.Remove($User.ADsPath)
    
    }
    
    }
    
    
  • #125390

    Moderator
    Points: 175
    Team MemberHelping Hand
    Rank: Participant

    As others have mentioned, you need to remove the -WhatIf.
    Unsolicited advice, don't just take scripts and run them, take time to read it and understand it. I put the -WhatIf in there on purpose as you should be testing.

  • #126545

    Participant
    Points: 32
    Rank: Member

    Thanks a lot, Script is working fine.

You must be logged in to reply to this topic.