Удалить всех бывших сотрудников из ВСЕХ групп рассылки - PullRequest
4 голосов
/ 21 февраля 2012

Итак, сегодня мне было поручено удалить всех бывших сотрудников в домене (у них есть собственная папка в AD) из всех их DL.Есть ли способ сделать это быстро, или, по крайней мере, быстрее, чем проверить каждого по отдельности и перейти к элементу> удалить все?

Спасибо

Изменить, чтобы добавить больше информации:

822 пользователям необходимо обновить вкладку «Участник», чтобы удалить их из всех списков рассылки.Моей команде из 5 человек (служба поддержки) понадобится примерно неделя, чтобы разобраться с нашей и без того огромной рабочей нагрузкой.Примерный путь к папке со всеми бывшими сотрудниками:

BusinessName.local \ MyBusiness \ Users \ Ex-Employees \

Если нужна какая-либо другая информация, я был бы более чем счастливпредоставить его.

Редактировать 2: В системе более 250 DL, поэтому я не могу предоставить список, как по соображениям конфиденциальности, так и по функциональности.

1 Ответ

3 голосов
/ 01 марта 2012

Добавлен скрипт Если вы хотите использовать скрипты Powershell, вот код

Add-Type -AssemblyName System.DirectoryServices.AccountManagement

$directorySearcher = New-Object System.DirectoryServices.DirectorySearcher
$directorySearcher.SearchRoot = "LDAP://OU=YourOU,DC=YourDomain,DC=com"
$directorySearcher.PageSize = 1000
$directorySearcher.Filter = "(&(objectCategory=User))"
$directorySearcher.SearchScope = "Subtree"

$directorySearcher.PropertiesToLoad.Add("name")

$searchResults = $directorySearcher.FindAll()

foreach ($result in $searchResults)
{$objItem = $result.Properties
    "Name: " + $objItem.name

    $contextType = [System.DirectoryServices.AccountManagement.ContextType]::Domain
    $userPrincipal = [System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($contextType,$objItem.name)
    $userGroups = $userPrincipal.GetGroups()

    foreach($userGroup in $userGroups){
      if ($userGroup.IsSecurityGroup -eq 0) #Distribution Group Only
      {
        "Removing - " + $userGroup.SamAccountName
        $userGroup.Members.Remove($userPrincipal)
        $userGroup.Save()
      }
    }
}

для .Net вот код

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;

        }

    }
}

Пожалуйста, возьмите такжеобратите внимание, что в $directorySearcher.SearchRoot или sDefaultOU вам необходимо использовать подразделение (или то, что вы называете папкой), где находятся ваши бывшие сотрудники, я думаю, что в вашем случае это "LDAP://OU=Ex-Employees,OU=Users,OU=MyBusiness,DC=BusinessName,DC=local", если используется в Powershell, или "OU=Ex-Employees,OU=Users,OU=MyBusiness,DC=BusinessName,DC=local", если используетсяв коде .Net

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...