Script to remove a group of users from AD Group

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

Something like this should work. Not tested, make sure you try in test environment first.
[pre]
$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
}
}
[/pre]

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

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

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

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/

Hi Rajesh,

You can try below script which i use daily

[pre]

$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)

}

}

[/pre]

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.

Thanks a lot, Script is working fine.