Thursday, August 12, 2010

How to get Group Membership with DSQuery/DSGet

Recently I’ve been asked to put in place a batch script which could produce a recursive text report of all the members in one or more Active Directory groups.

Dsquery and Dsget are very useful commands for this kind of interaction with the Active Directory, and the can be used togheter on the same lcommand line. It is in fact possible to pipe Dsquery output to Dsget this way:

dsquery group –name *samplegroupname* | dsget group -members >> group_membership.txt

The problem with this is that if you want to redirect the output of this command to a text file you will get a list of group members but not the name of the groups they belong to.

So, the solution is to use a "for" cycle in a batch file. The group name is written to the text file before writing the group members names. Here's the batch file:

===========================
@echo off

if exist group_membership.txt del group_membership.txt

dsquery group >temp_groups.txt

for /f “tokens=*” %%g in (temp_groups.txt) do @echo %%g >> group_membership.txt && echo Members in this group: >> group_membership.txt && dsget group %%g -members >> group_membership.txt && echo **************************************** >> group_membership.txt

notepad group_membership.txt

===========================

The output of the batch file is automatically opened in Notepad. Just remember to put all the "for" cycle on one line only!

2 comments:

  1. Thank you. This batch script is very useful!!!

    ReplyDelete
  2. Awesome! How do we go one step further and feed the members through dsget contact or dsget user and pull some more info like full name, email, telephone, location etc?

    Ideally end up with a table that could get pulled into excel and have group1 member1 name phone email etc so you could easily filter on group and members with contact info. Thanks!

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...