Solved

remove user from list of groups

Posted on 2016-10-27
2
25 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 69

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

Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

Question has a verified solution.

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

The article will show you how you can maintain a simple logfile of all Startup and Shutdown events on Windows servers and desktops with PowerShell. The script can be easily adapted into doing more like gracefully silencing/updating your monitoring s…
Active Directory replication delay is the cause to many problems.  Here is a super easy script to force Active Directory replication to all sites with by using an elevated PowerShell command prompt, and a tool to verify your changes.
Along with being a a promotional video for my three-day Annielytics Dashboard Seminor, this Micro Tutorial is an intro to Google Analytics API data.
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

810 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