Tuesday, April 9, 2013

Remove distribution group membership from users on an OU.




This power shell code will remove membership of distribution lists from all users in an OU.



Add-Type -AssemblyName System.DirectoryServices.AccountManagement

$directorySearcher = New-Object System.DirectoryServices.DirectorySearcher
$directorySearcher.SearchRoot = "LDAP://OU=EX-Employees,DC=UR-domainname,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()
      }
    }
}