Batch Script – How to Check if the Current User is a Member of a Group

Here is a batch script, using only DOS commands, to check if the current user is a member of a specific group. The way it is currently written, you can call a batch file containing this code using the CALL command and pass the short NetBIOS domain name (or possibly the computer name if it is a local account) and the group name to search for as arguments, and it will return a “1” if the user is a member of the specified group and “0” if they are not. Just be sure to put quotes around any group name that contains any spaces.

An example of how to call the script from within another script:

call "%USERPROFILE%\Desktop\is_group_member.bat" "yourDomain" "domain users"

If you wanted to call on this script and set the value as a variable in another script, you could do something like:

@ECHO OFF
FOR /F %%a IN ('call "%USERPROFILE%\Desktop\is_group_member.bat" "xyz" "sales"') DO SET "VAR=%%a"
ECHO %VAR%

is_group_member.bat

@ECHO OFF
IF [%1]==[] ( 
	ECHO No domain argument given.
	GOTO :EOF
) ELSE (
	SET "DOMAIN=%~1"
)
IF [%2]==[] ( 
	ECHO No search argument given.
	GOTO :EOF
) ELSE (
	SET "GROUPNAME=%~2"
)
FOR /F "tokens=1 delims=," %%g IN ('whoami /groups /fo csv /nh') DO FOR /F %%a IN ('@ECHO %%~g ^| findstr /I /R /C:"^%DOMAIN%\\*%GROUPNAME%\>" ^| FIND /C /V "DefNotThisSTRING!1234"') DO IF %%a==1 ( ECHO 1 & EXIT /B 1 )
GOTO :END

:END
ECHO 0
EXIT /B 0

Leave a Reply