remove Users from All ad groups except 2

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
[pre]

$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
}
}
}
[/pre]
thanks for your assistance

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

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

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.

thanks Stuard for the tip that solved my issue
Best regards

Paul