Tuesday, June 26, 2012

Bulk adding users to a domain group based on their email address

This is a quick script I threw together to help out someone with adding two thousand users to a group based on an email list. As you may notice, the format of the email and the domain DN is specified here, so if you want to use it in your environment, change the "contoso" parts to whatever is valid for your forest. This script assumes that the group that you want to add users to is a uniquely named group, as I didn't write anything to handle multiple groups in different domains with the same CN value. The script will take the email addresses from a text file (one per line) and add them to the group. If the email can't be found, or group can't be modified it will provide error details on a per email basis.

#requires -version 2

#Bulk add by email address value

 [parameter(mandatory=$true)][ValidateScript({Test-path $_ -PathType Leaf})]$userlist,
 [parameter(mandatory=$true)][ValidateScript( {
  #This validator will check AD to see if the group exists, and it will set $script:tgtgrp to the object that
  #will be modified
  $validatesearcher = New-Object directoryservices.DirectorySearcher("GC://dc=contoso,dc=com")
  $validatesearcher.filter = "(&(objectclass=group)(cn=$_))"
  $script:tgtgrp = $validatesearcher.findone()
  return $tgtgrp

$script:tgtgrp = [adsi]$script:tgtgrp.path
$users = get-Content $userlist
$de = New-Object directoryservices.DirectoryEntry("GC://dc=contoso,dc=com")
$searcher = New-Object directoryservices.Directorysearcher($de)
foreach ($user in $users) {
 try {
  if ($user -notmatch "@contoso.com") {
   throw "Entry: $user  is not a valid email address"
  $searcher.filter = "(&(objectclass=user)(proxyaddresses=SMTP:$user))"
  $userobj = $searcher.findone()
  if ($userobj -eq $null) {
   throw "Entry: $user  could not be found in active directory"
   try {
    $script:tgtgrp.properties["member"].add($userobj.properties.distinguishedname[0]) |out-null
   } catch {
    throw "Error occurred when trying to add member:$($userobj.properties.distinguishedname[0]) to group"
 } catch {
  Out-Default -InputObject $_.exception

 Add-BulkUserByEmail will add users to a specified group (Used quotes around groups with spaces in them)
 from a text file list of user email addresses (one user per line)
 The full path to the userlist text file (ex: c:\temp\userlist.txt)
.PARAMETER Groupname
 The name of the group object in active directory (CN attribute value).  This name must be unique in the 
 forest, or the wrong group may be selected

 Add-BulkUserByEmail -userlist c:\temp\userlist.txt -groupname "My Distro List group"

No comments:

Post a Comment