Solved

remove user from list of groups

Posted on 2016-10-27
2
16 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 68

Accepted Solution

by:
Qlemo earned 500 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

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

How to sign a powershell script so you can prevent tampering, and only allow users to run authorised Powershell scripts
In this previous article (https://oddytee.wordpress.com/2016/05/05/provision-new-office-365-user-and-mailbox-from-exchange-hybrid-via-powershell/), we made basic license assignments to users in O365. When I say basic, the method is the simplest way …
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

708 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

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now