December 2008

Thursday, December 4, 2008

Export Exchange query-based distribution group members to a CSV file


This is a script I run internally to generate reports of query-based distribution group members as CSV files (viewable in Excel).

You'll need the free ADFIND tool from joeware for this script to run.
http://www.joeware.net/freetools/tools/adfind/index.htm

You'll also need to change the following line to reflect the proper LDAP base DN for your domain.
SET BASEDN="dc=domain,dc=local"

Script: Run-QBDG-Export.bat
@ECHO OFF
SETLOCAL
IF "%1" EQU "" (
ECHO.
ECHO ERROR!
ECHO Parameter required ^
ECHO.
ECHO Usage: Run-QBDG-Export.bat ^
ECHO.
GOTO :EOF
)

REM CHANGE THIS LINE TO MATCH YOUR DOMAIN
SET BASEDN="dc=domain,dc=local"
SET CMDLINE=ADFIND -b %BASEDN% -f "cn=%1*" -nodn cn
%CMDLINE% >%1-GETGROUPS.txt 2>NUL
IF EXIST %1-GETGROUPS.txt (
FIND /I "0 Objects returned" %1-GETGROUPS.txt
IF ERRORLEVEL 1 (
GOTO START_SEARCH
) ELSE (
ECHO ERROR: Could not query Active Directory for groups with %1*
GOTO END
)
) ELSE (
ECHO ERROR: Could not query Active Directory for groups with %1*
GOTO END
)

:START_SEARCH
FOR /F "usebackq tokens=1*" %%A IN (`type %1-GETGROUPS.txt ^| FIND /I ">cn:"`) DO (
SET GRP_OBJ=%%B
CALL :GET_MEMBERS %%B
)

FOR /F "tokens=1,2 delims=:" %%A in ("%TIME%") DO (
SET MYTIME=%%A:%%B
)
GOTO END

:GET_MEMBERS
SET FLT_QRY_OBJ="msExchDynamicDLFilter:"
SET FLT_DN_OBJ="msExchDynamicDLBaseDN:"

SET FLT_QRY_CMD=ADFIND -b %BASEDN% -f "cn=%GRP_OBJ%"
REM GET QUERY STRING
%FLT_QRY_CMD% > %1-ADINFO.txt 2>NUL

FOR /F "usebackq tokens=1*" %%A IN (`type %1-ADINFO.txt ^| FIND /I %FLT_QRY_OBJ%`) DO (
SET QRY_STR="%%B"
)
REM GET QUERY BASE DN
FOR /F "usebackq tokens=1*" %%A IN (`type %1-ADINFO.txt ^| FIND /I %FLT_DN_OBJ%`) DO (
SET QRY_DN="%%B"
)

ECHO Running the following query:
ECHO ------------------------------------------------
ECHO CN: %GRP_OBJ%
ECHO DN: %QRY_DN%
ECHO QS: %QRY_STR%
ECHO.
IF EXIST "%GRP_OBJ%.csv" (
DEL /Q "%GRP_OBJ%.csv"
)
ECHO Creating export file...
ADFIND -csv -b %QRY_DN% -f %QRY_STR% sn givenName mail title physicalDeliveryOfficeName employeeID -nodn >"%GRP_OBJ%.csv" 2>NUL
ECHO Done.
ECHO.
ECHO.
IF NOT EXIST "%GRP_OBJ%.csv" (
ECHO Could not create "%GRP_OBJ%.csv"
ECHO.
ECHO Press any key to continue or Ctrl-C to quit...
PAUSE >NUL 2>NUL
)
REM PAUSE
GOTO :EOF

:END
DEL /Q %1-GETGROUPS.txt >NUL 2>NUL
DEL /Q %1-BODY.TXT >NUL 2>NUL
DEL /Q %1-ADINFO.txt >NUL 2>NUL

ENDLOCAL