JSI Tip 7226. What local and domain groups does the currently logged on domain user belong to, including nested groups?

Using Showgrps from the resource kit, Directory Service command-line tools from Windows Server 2003, and Nested.bat, I have scripted GroupMembership.bat to return the list of local and domain groups that the currently logged on domain users is a member of, including nested domain groups.

When you type GroupMembership, a list similar to the following is returned:

"JSIINC\Accounts Payables" D
"JSIINC\Domain Users" D
"JSI007\Everyone" L
"JSIINC\Everyone" D
"JSI007\Users" L
"JSIINC\accountants" N
where the group begins with either the NetBIOS domain name or computer name, and the letter can be:
E - Error, the domain user could not be found.
D - The group is from Active Directory.
L - The group is local to the logged on computer.
N - The group is a nested Active Directory group.
To use GroupMembership.bat in a script, use a command similar to the following:

for /f "Tokens=*" %%g in ('GroupMembership') do call :your_routine %%g

where the label or routine name your_routine could contain:

@echo %1 %2

GroupMembership.bat contains:

@echo off
set usr=%username%
set dn=
for /f "Tokens=*" %%u in ('dsquery user -samid "%usr%"') do set dn=%%u
if not defined dn @echo "Domain User %UserName% NOT Found" E&endlocal&goto :EOF
for /f "Tokens=1-6 Delims=," %%a in ('@echo %DN%') do set d1=%%c&set d2=%%d&set d3=%%e&set d4=%%f
set d1=%d1:"=%
if "%d1:~0,3%" EQU "DC=" set domain=%d1:~3%&goto continue
set d2=%d2:"=%
if "%d2:~0,3%" EQU "DC=" set domain=%d2:~3%&goto continue
set d3=%d3:"=%
if "%d3:~0,3%" EQU "DC=" set domain=%d3:~3%&goto continue
set d4=%d4:"=%
if "%d4:~0,4%" EQU "DC=" set domain=%d3:~3%&goto continue
set domain=UNKOWN
set domusr="%domain%\%usr%"
for /f "Skip=2 Tokens=*" %%g in ('showgrps %domusr%') do set grp=%%g&call :dorl
for /f "Tokens=*" %%g in ('nested %usr%') do call :nest %%g
goto :EOF
call set wrk=%%grp:%computername%=%%
set type=L
if "%wrk%" EQU "%grp%" set type=D
if "%grp:~0,1%" EQU "\" @echo "%Computername%%grp%" L&set grp=%domain%%grp%
@echo "%grp%" %type%
goto :EOF
@echo %1 N

Hide comments


  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.