DCSIMG
Bulk add user accounts from a file to security group using batch - Windowmaker's blog

Bulk add user accounts from a file to security group using batch

If you have a file containing the names of users (sAMAccountName) and you want to add all of them to a specific group in AD, here is a batch script that might make your life easier:
 
:: GrpFromFile.CMD - Guy Teverovsky - January 2007
::
:: Add users from a file to specific group

@echo off

setlocal ENABLEDELAYEDEXPANSION
setlocal ENABLEEXTENSIONS

if "%1"=="" goto :SYNTAX
if "%1"=="/?" goto :SYNTAX

echo/

:: Define initial environment
set groupname=%1
set filename=%2
set scriptname=GrpFromFile

:: Determine if supplied arguments were sufficient
if "%groupname%"=="" (
  echo/
  echo ERROR - Insufficient arguments
  goto :SYNTAX
)

if "%filename%"=="" (
  echo/
  echo ERROR - Insufficient arguments
  goto :SYNTAX
)

if not exist "%filename%" (
  echo/
  echo ERROR - File not found
  goto :SYNTAX
)

:: Locate critical executables
for %%e in (dsquery.exe dsget.exe) do (
  set where="%%~$PATH:e"
  if "!where!"=="""" (
    echo ERROR - Required executable, "%%e", not located within the path
    goto :END
  )
)

FOR /F "TOKENS=*" %%G IN ('dsquery group -name %groupname%') DO SET groupdn=%%~G
if "x%groupdn%" == "x" (
  echo/
  echo ERROR - Group not found
  goto :END
)

  
for /f "delims=" %%i in (%filename%) do (
  :: Search for the user and add to group
  FOR /F "TOKENS=*" %%U IN ('dsquery user -samid %%i') DO dsmod group "%groupdn%" -addmbr "%%~U" -c
)

goto :END

:SYNTAX
echo/
echo SYNTAX - %scriptname% [Group] [File]
echo/
echo * [Group] is the group to add accounts to
echo * [File] is the file containing the list of user accounts
echo/
echo e.g. - %scriptname% grpAllUsers userlist.txt
echo/

:END
 
 
The script can be downloaded from here.
 
Published Sunday, January 14, 2007 2:52 PM by Guy Teverovsky

Comments

Saturday, January 17, 2009 12:01 PM by zaheer

# re: Bulk add user accounts from a file to security group using batch

Hey I tried using this in windows 2003 Active Directory Child Domain but it Doesnt seem to work gives Eror as File Not Found I have Given the Location of File

Monday, February 02, 2009 2:48 PM by aamer

# re: Bulk add user accounts from a file to security group using batch

my file name for example is test.txt located on the c drive c:\test.txt containing a list of users and the group to which i want to add is testgroup, how should i modify the file

Monday, February 02, 2009 4:09 PM by manthiramoorthy

# re: Bulk add user accounts from a file to security group using batch

scripit file

Monday, February 02, 2009 4:10 PM by manthiramoorthy

# re: Bulk add user accounts from a file to security group using batch

scripit is superb using for win2003