Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Remove Userfrom all groups Powershell

Posted on 2016-08-03
6
Medium Priority
?
67 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 41

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
NEW Veeam Agent for Microsoft Windows

Backup and recover physical and cloud-based servers and workstations, as well as endpoint devices that belong to remote users. Avoid downtime and data loss quickly and easily for Windows-based physical or public cloud-based workloads!

 
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 2000 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

Problems using Powershell and Active Directory?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

Question has a verified solution.

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

Windows 10 came with  a lot of built in applications, Some organisations leave them there, some will control them using GPO's. This Article is useful for those who do not want to have any applications in their image (example:me).
In previous parts of this Nano Server deployment series, we learned how to create, deploy and configure Nano Server as a Hyper-V host. In this part, we will look for a clustering option. We will create a Hyper-V cluster of 3 Nano Server host nodes w…
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…
In this video, Percona Solution Engineer Dimitri Vanoverbeke discusses why you want to use at least three nodes in a database cluster. To discuss how Percona Consulting can help with your design and architecture needs for your database and infras…

604 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