Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections;
- using System.Linq;
- using System.Text;
- using System.DirectoryServices;
- using System.DirectoryServices.AccountManagement;
- namespace RemoveFromDistributionGroups
- {
- class Program
- {
- private static string sDomain;
- private static string sDefaultOU;
- private static string sServiceUser;
- private static string sServicePassword;
- static void Main(string[] args)
- {
- try
- {
- Console.Write("Type your Domain (i.e: yourcompany.com) ");
- sDomain = Console.ReadLine();
- Console.Write("Type the OU you want to use: (i.e: OU=yourou,DC=yourcompany,DC=com)");
- sDefaultOU = Console.ReadLine();
- Console.Write(@"Username: (i.e.: YOURDOMAIN\Raymund )");
- sServiceUser = Console.ReadLine();
- Console.Write("Password: ");
- sServicePassword = Console.ReadLine();
- foreach (UserPrincipal user in GetAllUsers())
- {
- Console.WriteLine("Processing User : " + user.Name);
- foreach (GroupPrincipal group in GetUserGroups(user))
- {
- if (group.IsSecurityGroup == false) //Distribution Group
- {
- group.Members.Remove(user);
- group.Save();
- }
- }
- }
- Console.WriteLine("Done! Press a key to exit");
- Console.ReadLine();
- }
- catch (Exception ex)
- {
- Console.WriteLine("Error Encountered : " + ex.Message);
- Console.WriteLine("Press a key to exit");
- Console.ReadLine();
- }
- }
- public static PrincipalContext GetPrincipalContext(string sOU)
- {
- PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain, sDomain, sOU, ContextOptions.Negotiate, sServiceUser, sServicePassword);
- return oPrincipalContext;
- }
- public static ArrayList GetAllUsers()
- {
- ArrayList myItems = new ArrayList();
- PrincipalSearcher oPrincipalSearcher = new PrincipalSearcher();
- UserPrincipal oUserPrincipal = new UserPrincipal(GetPrincipalContext(sDefaultOU));
- oUserPrincipal.SamAccountName = "*";
- oUserPrincipal.Enabled = true;
- oPrincipalSearcher.QueryFilter = oUserPrincipal;
- ((DirectorySearcher)oPrincipalSearcher.GetUnderlyingSearcher()).PageSize = 5000;
- PrincipalSearchResult<Principal> oPrincipalSearchResults = oPrincipalSearcher.FindAll();
- foreach (Principal oResult in oPrincipalSearchResults)
- {
- myItems.Add(oResult);
- }
- return myItems;
- }
- public static ArrayList GetUserGroups(UserPrincipal oUserPrincipal)
- {
- ArrayList myItems = new ArrayList();
- PrincipalSearchResult<Principal> oPrincipalSearchResult = oUserPrincipal.GetGroups();
- foreach (Principal oResult in oPrincipalSearchResult)
- {
- myItems.Add(oResult);
- }
- return myItems;
- }
- }
- }
Add Comment
Please, Sign In to add comment