Powershell Script - remove user from distribution groups

Stewart_HendersonNO1
Stewart_HendersonNO1 used Ask the Experts™
on
Powershell script to remove user from all distribution groups
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
Try this:
$adUser = Get-ADUser jdoe -Properties memberOf
$remove = $adUser |
	Select-Object -ExpandProperty memberOf |
	Get-ADObject -Property groupType |
	Where-Object {2, 4, 8 -contains $_.groupType} |
	Select-Object -ExpandProperty DistinguishedName
If ($remove) {Remove-ADPrincipalGroupMembership -Identity $adUser -MemberOf $remove}

Open in new window

So if the use is j.bloggs then the script to execute is as per below in its entirety ? and this removes the user from all the 'distribution groups' ?

$adUser = Get-ADUser j.bloggs -Properties memberOf
$remove = $adUser |
      Select-Object -ExpandProperty memberOf |
      Get-ADObject -Property groupType |
      Where-Object {2, 4, 8 -contains $_.groupType} |
      Select-Object -ExpandProperty DistinguishedName
If ($remove) {Remove-ADPrincipalGroupMembership -Identity $adUser -MemberOf $remove}
Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
Yes.
If you want to see the groups beforehand, comment out the last line, and just check the contents of $remove (-WhatIf won't help in this case, it will only tell you that it will remove the user from all groups passed, but not which groups were actually passed):
$adUser = Get-ADUser j.bloggs -Properties memberOf
$remove = $adUser |
	Select-Object -ExpandProperty memberOf |
	Get-ADObject -Property groupType |
	Where-Object {2, 4, 8 -contains $_.groupType} |
	Select-Object -ExpandProperty DistinguishedName
$remove
#If ($remove) {Remove-ADPrincipalGroupMembership -Identity $adUser -MemberOf $remove}

Open in new window

Many thanks for the support on this question.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial