remove Users from All ad groups except 2

Welcome Forums General PowerShell Q&A remove Users from All ad groups except 2

Viewing 4 reply threads
  • Author
    Posts
    • #200363
      Participant
      Topics: 9
      Replies: 14
      Points: 94
      Rank: Member

      Hi
      I have found this script which works perfect forĀ  to remove the user from all groups but 1.
      However I need to remove the user from All groups but 2 what do I need to adjust to keep just 2 groups active
      Domain users and syncedToAzure needs to remain

      
      $users = import-csv c:\temp\toRemove.csv
      
      foreach ($user in $users)
      {
      $adgroups = Get-ADPrincipalGroupMembership -Identity $user.SamAccountName
      foreach ($singlegroup in $adgroups)
      {
      if ($singlegroup.SamAccountName -notlike “*Domain Users*”)
      {
      Remove-ADPrincipalGroupMembership -Identity $user.SamAccountName -MemberOf $singlegroup.SamAccountName -confirm:$false
      }
      }
      }
      

      thanks for your assistance

    • #200387
      Participant
      Topics: 5
      Replies: 11
      Points: 67
      Rank: Member

      Hi,

      As I recall, you can do it with the -Or option, changing that line:

      if ($singlegroup.SamAccountName -notlike "*Domain Users*" -Or $singlegroup.SamAccountName -notlike "syncedToAzure")
      

      Hope it helps

    • #200405
      Participant
      Topics: 9
      Replies: 14
      Points: 94
      Rank: Member

      when I’m trying this I get the following error

      WARNING: Could not remove member(s) from ADGroup: ‘CN=Domain Users,CN=Users,DC=synamedia,DC=com’. Error is: ‘The user cannot be removed from a group because the group is currently th
      e user’s primary group’.
      Remove-ADPrincipalGroupMembership : Could not remove member(s) to one or more ADGroup.
      At C:\Users\username\Documents\removeUsersFromGroup.ps1:14 char:5
      + Remove-ADPrincipalGroupMembership -Identity $user.SamAccoun …
      + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo : OperationStopped: (Microsoft.Activ…ement.ADGroup[]:ADGroup[]) [Remove-ADPrincipalGroupMembership], ADException
      + FullyQualifiedErrorId : 1,Microsoft.ActiveDirectory.Management.Commands.RemoveADPrincipalGroupMembership

    • #200483
      Participant
      Topics: 0
      Replies: 14
      Points: 116
      Rank: Participant

      Try changing the -Or to -And . That should do the trick. You need the group name to not be ‘Domain Users’ and also not be ‘synchedToAzure’.

      Regards,

      Stuart.

    • #200489
      Participant
      Topics: 9
      Replies: 14
      Points: 94
      Rank: Member

      thanks Stuard for the tip that solved my issue
      Best regards

      Paul

Viewing 4 reply threads
  • You must be logged in to reply to this topic.