Solved

Remove Userfrom all groups Powershell

Posted on 2016-08-03
6
49 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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 40

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
Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

 
LVL 13

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 13

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

[Webinar] Code, Load, and Grow

Managing multiple websites, servers, applications, and security on a daily basis? Join us for a webinar on May 25th to learn how to simplify administration and management of virtual hosts for IT admins, create a secure environment, and deploy code more effectively and frequently.

Question has a verified solution.

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

This article explains how to prepare an HTML email signature template file containing dynamic placeholders for users' Azure AD data. Furthermore, it explains how to use this file to remotely set up a department-wide email signature policy in Office …
A recent project that involved parsing Tableau Desktop and Server log files to extract reusable user queries for use in other systems. I chose to use PowerShell to gather the data, and SharePoint to present it...
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…
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…

738 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