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

14 בינואר 2007

4 תגובות

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.

 

הוסף תגובה
facebook linkedin twitter email

כתיבת תגובה

האימייל לא יוצג באתר. שדות החובה מסומנים *

4 תגובות

  1. zaheer17 בינואר 2009 ב 12:01

    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

    הגב
  2. aamer2 בפברואר 2009 ב 14:48

    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

    הגב
  3. manthiramoorthy2 בפברואר 2009 ב 16:10

    scripit is superb using for win2003

    הגב