« Gary Hill and the AIDS/LIFECYCLE ride | Photograph of the Week »

Scripting moving objects in AD

During an Exchange migration I needed a script to move 200 users into an OU indicating they were migrated. Since the source OU's for these users is all over the place, I took to placing a custom attribute and doing an ADUC saved query (LDAP) search to find them, then select in mass and moved them.

Throw in AD replication delays and such and, why not do the whole thing from a script? So, here's a really simple way to move objects in AD.

Requires:

  • ADmod.exe and Adfind.exe from Joeware.net (free).
  • This script uses texttools32 from Firefly software. You can use any equivalent command line text editor with some minor changes.

The Code:

@echo off
::REM --------- Begin sample batch script --------------
::REM Sample batch programming script
::REM (C)2006 John D. Seaman, Copylefted under terms of the GNU/GPL
::REM by John D. Seaman, www.japan-page.net/batch

::REM This script will take the userID (samAccountName) and look up the object DN in AD.
::REM It will then move it to the location specified in moveToDN.
::REM Create an input file (listing of userIDs) in a text file userlist.txt, one entry per line.

::REM Create log file
set _log=moveUser.log

::REM Set variables here (replace with your domain info)
set _baseDN="DC=mydomain,DC=com"
set _moveToDN="OU=PutUsersHere,DC=mydomain,DC=com"
set _dc=myDomainController

::REM Set up a loop and process users

for /f %%i in (userlist.txt) do call :moveUser %%i

echo.
echo Completed

echo Cleaning up...
del /q _out.txt _userDN*.txt

echo.
pause
goto :EOF


::REM -----------------------------------------------------------------------------------------


:moveUser
::REM Start

echo Now moving user %1...

::REM ---------------------
::REM Get username base DN:
::REM ---------------------

::REM Time to get jiggy...

adfind -b %_baseDN% -f "(samAccountName=%1)" -dn >_out.txt

::REM Extract only the line containing the user object DN
type _out.txt | find "dn:" >_userDN.txt

::REM Fix the UserDN by nuking the first 3 characters...
::REM This example uses t.exe, AKA Texttools32 from Firefly Software. You might
::REM also be able to use the GNU 32 version of SED, etc.


type _userDN.txt | t repl 'dn:' '' >_userDN1.txt

for /f "delims=@" %%i in (_userDN1.txt) do (
echo User %1 DN is %%i
echo User %1 DN is %%i>>%_log%
echo Moving object %1...>>%_log%
admod.exe -h %_dc% -b %%i -move %_moveToDN%
)

goto :EOF


:EOF

This script will modify objects in AD, be very careful what you are doing. The author takes absolutely no responsibility for use of this script. This script is provided as-is for educational purposes only.

Post a comment

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)