Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

remove user from list of groups

Posted on 2016-10-27
2
Medium Priority
?
44 Views
Last Modified: 2016-10-27
I am looking to remove a user from a list of groups. He may be part of a few of them. But if the user is not part of one of the groups the script seems to stop.  I would like to attempt to remove the user from all of the groups even if the user is not part of them.  

$script:groups = @("group1", "group2","group3")
foreach ($adgroups in $groups) { remove-adgroupmember $adgroups –members $a -confirm:$false }

If it makes it any easier all of the groups are part of a parent group. So group2 and group3 are part of group1.  I dont know if there is a way to just remove a user from the parent group and all sub groups.
0
Comment
Question by:Roccat
2 Comments
 
LVL 71

Accepted Solution

by:
Qlemo earned 2000 total points
ID: 41862457
Just to "silently ignore" errors is one way:
$script:groups = @("group1", "group2","group3")
foreach ($adgroups in $groups) { remove-adgroupmember $adgroups –members $a -confirm:$false -EA SilentlyContinue } 

Open in new window

The more "polite" way is to get the groups the user is a member of, then  check against the removal list, and run only if necessary.
$script:groups = @("group1", "group2","group3")
(get-aduser $a -property MemberOf).MemberOf |
  % { $_.Split(',')[0] -replace 'CN='} |
  ? { $groups -contains $_ } |
  % { Remove-ADGroupMember $_ -Members $a -Confirm:$false }

Open in new window

2
 

Author Closing Comment

by:Roccat
ID: 41862732
Thank you!
0

Featured Post

Creating Active Directory Users from a Text File

If your organization has a need to mass-create AD user accounts, watch this video to see how its done without the need for scripting or other unnecessary complexities.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Previously, on our Nano Server Deployment series, we've created a new nano server image and deployed it on a physical server in part 2. Now we will go through configuration.
Transferring FSMO roles is done when an admin wants to split roles between certain Domain Controllers or the Domain Controller holding the Roles has been forcefully demoted using dcpromo / forceremoval
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an anti-spam), the admin…

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question