Added Script If you want to use Powershell scripts, here is the code
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)
for .Net is code
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 (ie: yourcompany.com) "); sDomain = Console.ReadLine(); Console.Write("Type the OU you want to use: (ie: OU=yourou,DC=yourcompany,DC=com)"); sDefaultOU = Console.ReadLine(); Console.Write(@"Username: (ie: 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)
Also note that in $directorySearcher.SearchRoot or sDefaultOU you need to use the OU (or what you call the folder) where your former employees are located, I think in your case it is "LDAP://OU=Ex-Employees,OU=Users,OU=MyBusiness,DC=BusinessName,DC=local" if it is used in Powershell or "OU=Ex-Employees,OU=Users,OU=MyBusiness,DC=BusinessName,DC=local" if used in .Net code
source share