Separating AD users into groups

powershell

In our AD we have many users, all of them are unified in one general mailgroup “visi”. One day I was tasked to split users into english and lithuanian groups, so that emails in my language wouldn’t bother those who can’t read them :P
It was easy with my newly acquired Powershell skill, and we were dividing people into groups by their departments, so I knew the english speaking departments, all I had to do was list out all the people and add them to “visilt” and “visien” groups according by their departments.

Import-module ActiveDirectory
 
$users = Get-ADUser -Filter {(Enabled -eq "True")} -SearchBase "OU=Folder,DC=subdomain,DC=domain,DC=lt" -Server subdomain -Properties Name, MemberOf, DistinguishedName | Select Name, MemberOf, DistinguishedName
foreach ($user in $users) {
    if (($user.Name -notlike "0*") -and ($user.Name -notlike "WTF*")) {
        if (($user.MemberOf -notcontains "CN=visien,OU=MailGrupes,DC=subdomain,DC=domain,DC=lt") -and (($user.MemberOf -like "CN=F-*") -or ($user.MemberOf -like "CN=E-*"))) {
            # jeigu jis yra uzsienietis (grupeje F-* and E-*) tai dedam ji i visien
            Write-Host "Ne Lietuvis: $($user.Name)"
            Add-ADGroupMember -Identity "CN=visien,OU=MailGrupes,DC=subdomain,DC=domain,DC=lt" -Member $user.DistinguishedName -Server subdomain -ErrorAction SilentlyContinue
            # Write-Host "-------------------------"
            # exit
        } elseif (($user.MemberOf -notcontains "CN=visien,OU=MailGrupes,DC=subdomain,DC=domain,DC=lt") -and ($user.MemberOf -notcontains "CN=visilt,OU=MailGrupes,DC=subdomain,DC=domain,DC=lt")) {
            # jeigu jis ne uzsienietis ir nera grupeje visilt, tai dedam i ta grupe
            Write-Host "Lietuvis: $($user.Name)"
            Add-ADGroupMember "CN=visilt,OU=MailGrupes,DC=subdomain,DC=domain,DC=lt" -Member $user.DistinguishedName -Server subdomain -ErrorAction SilentlyContinue
            # Write-Host "-------------------------"
            # exit
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *