DCSIMG
January 2007 - Posts - Windowmaker's blog

January 2007 - Posts

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.