Sunday, July 14, 2013

Export Active Directory Groups with their Members

Many times I have seen situations when there is a need to audit Active Directory Groups.

In this blog I have included a batch script which will export all AD groups with their members into .csv file which you can open in Microsoft Excel and apply different filters.

:::: Batch Script Start ::::
SETLOCAL EnableDelayedExpansion

SET FileName=C:\Report.csv

FOR /F %%T IN ('DSQuery * -Filter "(&(objectClass=Group))" -Limit 0') DO SET /a AG+=1 >NUL
FOR /F %%T IN ('DSQuery * -Filter "(&(objectClass=Group)(^!member=*))" -Limit 0') DO SET /a EG+=1 >NUL
SET /a NE=!AG!-!EG!

ECHO Total Groups in Active Directory %AG% out of them %EG% are empty.&&ECHO.
ECHO Group,Members>"!FileName!"
TITLE Exporting !NE! Non-Empty AD Groups.

FOR /F "delims=" %%G IN ('DSQuery * -Filter "(&(objectClass=Group)(member=*))" -Limit 0') DO (
    FOR /F "delims=" %%v IN ('DSQuery * %%G -l -q -Attr Name -Limit 0') DO SET GN=%%v
    SET /a CT+=1 >NUL
    ECHO !CT!. Exporting: !GN!
    FOR /F "delims=" %%M IN ('DSGET Group %%G -Members') DO (
        FOR /F "delims=" %%U IN ('DSQuery * %%M -l -q -Attr displayName') DO (
        ECHO !GN!,%%U>>"!FileName!")))

TITLE Export complete.
ECHO.&&ECHO Export complete, please check '!FileName!' file.
:::: Batch Script End ::::
Copy above script and paste into Notepad and save it with any name having .cmd extension and execute it from command line.

Following one liners can be used to list group members.

To display group's distinguished name:

DSQuery Group -name GroupName

To display Group members:

DSQuery Group -name GroupName |DSGet Group -Members

To list group members's display name or usernames:

DSQuery Group -name GroupName |DSGet Group -Members |DSGet User -c -samID -display

If your group contains any other group (nested) then you might get message like following:

dsget failed: <group distinguished name> :The object class of the target does not match the one specified on the command line.

So to ignore and continue command operation I have included -c switch with above DSGet User statement.

If you want to include members of all nested groups then you can use -expand switch with DSGet Group statement which will recursively expanded list of members of the group.

DSQuery Group -name GroupName |DSGet Group -Members -expand |DSGet User -c -samID -display

To save output into file you can use dos redirection operator > with file name.

DSQuery Group -name GroupName |DSGet Group -Members -expand |DSGet User -c -samID -display >GroupMembers.txt