Solved

Remove Userfrom all groups Powershell

Posted on 2016-08-03
6
34 Views
Last Modified: 2016-08-04
I'm trying to run the following commend in code. I think I have the first part correct, but I don't know how to do the removal part. | % {Remove-ADPrincipalGroupMembership -Identity SaraDavis -MemberOf $_}

Get-ADPrincipalGroupMembership -Identity SaraDavis | % {Remove-ADPrincipalGroupMembership -Identity SaraDavis -MemberOf $_}
                                    
                  Command RemoveFromGroups = new Command("Get-ADPrincipalGroupMembership");
                        RemoveFromGroups.Parameters.Add("identity", user.adAccount.user.DistinguishedName);
                     

                        //add command to pipeline
                        pipeLine.Commands.Add(RemoveFromGroups);

                        //executes pipline
                        results = pipeLine.Invoke();
0
Comment
Question by:NickMalloy
6 Comments
 
LVL 16

Expert Comment

by:FOX
ID: 41741088
the command looks correct.  The should not be any space between %{
Did you right-click powershell and (run as administrator), did you run the command   Import-module ActiveDirectory
0
 
LVL 39

Expert Comment

by:footech
ID: 41741092
This should work.
Get-ADPrincipalGroupMembership -Identity SaraDavis | % {Remove-ADPrincipalGroupMembership -Identity SaraDavis -MemberOf $_.distinguishedName} 

Open in new window


Another way (added the -confirm parameter to avoid a prompt for each):
$user = "SaraDavis"
Get-ADUser $user -Properties MemberOf | ForEach { Remove-ADPrincipalGroupMembership -Identity $_.SamAccountName -MemberOf $_.MemberOf -Confirm:$false }

Open in new window

0
 

Author Comment

by:NickMalloy
ID: 41741096
I'm putting the powershell in a c@ command console application, so I'm more wondering how to format it for that? So far this is what I have

                        Command RemoveFromGroups = new Command("Get-ADPrincipalGroupMembership");
                        RemoveFromGroups.Parameters.Add("identity", user.adAccount.user.DistinguishedName);
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 12

Expert Comment

by:Dustin Saunders
ID: 41741127
If you're using c# is there a reason you're invoking Powershell and not doing the removal within your c# application?
0
 

Author Comment

by:NickMalloy
ID: 41741130
I am doing the removal through the application. I just want to invoke the command to do the removal. The script does a lot of things, this is just a small piece. I need to remove the user from all AD groups they are members of. The powershell script seems like the least taxing.
0
 
LVL 12

Accepted Solution

by:
Dustin Saunders earned 500 total points
ID: 41741164
I think it's going to be easier to keep it all in c#.  Update the LDAP in line 3 with your domain.
using System.DirectoryServices;

Open in new window


public void RemoveUserFromGroups(string sAMAccountName)
        {
            DirectoryEntry root = new DirectoryEntry("LDAP://dc=wizdev,dc=local", null, null);
            DirectorySearcher searcher = new DirectorySearcher(root, "(samaccountname=" + sAMAccountName + ")", new string[] { "memberOf" });
            SearchResultCollection results = searcher.FindAll();
            foreach (SearchResult result in results)
            {
                if (result.Properties.Contains("memberOf"))
                {
                    PropertyValueCollection groups = result.GetDirectoryEntry().Properties["memberOf"];
                    if (groups != null)
                    {
                        for (int i = 0; i < groups.Count; i++)
                        {
                            string groupDn = (string)groups[i];
                            DirectoryEntry group = new DirectoryEntry("LDAP://" + groupDn, null, null);
                            if (group != null)
                            {
                                group.Invoke("Remove", new object[] { result.Path });
                            }
                        }
                    }
                }
            }
        }

Open in new window


So you can use this syntax:
string user = "johntest_sample";
RemoveUserFromGroups(user);

Open in new window

0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
This article will help you understand what HashTables are and how to use them in PowerShell.
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

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

13 Experts available now in Live!

Get 1:1 Help Now