DCSIMG
Copying AD user group membership with dsquery and dsmod - Windowmaker's blog

Copying AD user group membership with dsquery and dsmod

 

A question was asked at Daniel Petri's forums about copying AD user's group membership using dsquery/dsmod tools. Having some spare time I have written a batch script that does just that - looks at memberOf attribute of source user account and joins the target account to those groups.

Important: if the source account is a member in a group that resides in another forest or the group is of Domain Local type, the fact is not reflected in the memberOf attribute and membership in those group will not be copied between accounts. The script is mosly usefull in single domain AD, where the caviats mentioned above do not apply.

Code:

:: CpGroups.CMD - Guy Teverovsky - December 2006
::
:: Copies group membership between user accounts

@echo off

setlocal ENABLEDELAYEDEXPANSION
setlocal ENABLEEXTENSIONS

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

echo/

:: Define initial environment
set source_usr=%1
set target_usr=%2
set scriptname=CpGroups


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

if "%target_usr%"=="" (
  echo/
  echo ERROR - Insufficient arguments
  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 "delims=" %%i in ('dsquery user -samid %source_usr%') do (
  setlocal DISABLEEXTENSIONS
  set source_usr_dn=%%i
  setlocal ENABLEEXTENSIONS
)

if %source_usr_dn%=="" (
  echo/
  echo ERROR - Source user account not found
  goto :END
)

for /f "delims=" %%i in ('dsquery user -samid %target_usr%') do (
  setlocal DISABLEEXTENSIONS
  set target_usr_dn=%%i
  setlocal ENABLEEXTENSIONS
)

if %target_usr_dn%=="" (
  echo/
  echo ERROR - Target user account not found
  goto :END
)


for /f "delims=" %%i in ('dsget user %source_usr_dn% -memberof') do (
  dsmod group %%i -addmbr %target_usr_dn%
)

goto :END

:SYNTAX
echo/
echo SYNTAX - %scriptname% [source account samid] [target account samid]
echo/
echo * [source account samid] is the account to copy the group membership from
echo * [target account samid] is the account to copy the group membership to
echo/
echo e.g. - %scriptname% jdoe bsmith
echo/

:END

Download the script

Published Friday, December 22, 2006 6:14 PM by Guy Teverovsky

Comments

No Comments