Last Updated on 2016-01-13.
Scenario
According to a group membership of the current Windows workstation user, you want to run certain commands in a Windows Batch file (cmd, .bat).
Solutions
1)
Use file isMember.exe from here. The link also includes a usage example.
2)
If you do not trust foreign .exe files, create a file isMember.bat e.g. with this content (original script):
@echo off set i=0 set group=%1 set user=%username% echo Checking if %user% is member of %group%... for /f %%f in ('"net user %user% /domain | findstr /i %group%"') do set /a i=%i%+1 if %i% gtr 0 (goto :member) :nomember echo %user% is not member of %group% exit /B 0 :member echo %user% is member of %group% exit /B 1
Then run isMember.bat, your group name should be the parameter. You can then use the return code of this script in another one (variable ERROR_LEVEL). Make sure you run it with “call isMember.bat” command, without “call” your main script would also be exited.
Please note the “net user” command used above might cut long group names, so solution 1 could be a better way.
3)
Other ways, but also have to be parsed:
gpresult /user myAccount /r
whoami /groups
for /f "tokens=1 delims=," %g in ('whoami /groups /fo csv /nh') do @echo "%~g"
Hi there. Your script always gives false positive result 🙁
Better to use net group check:
for /f %%f in (‘”net group %ADgroup% /domain | findstr /i %ADuser%”‘) do set /a i=%i%+1
how can you do this for PC account not user?
:: if user is a member of group associated with S-1-5-21-167335082-2949395101-2103287839-2219 map drive O:
for /f “tokens=* delims=” %%i in (‘whoami /groups ^| findstr “S-1-5-21-167335082-2949395101-2103287839-2219″‘) do (
IF errorlevel 0 if not errorlevel 1 call :mapo
)
:: if user is a member of group associated with S-1-5-21-167335082-2949395101-2103287839-1384 map drive L:
for /f “tokens=* delims=” %%i in (‘whoami /groups ^| findstr “S-1-5-21-167335082-2949395101-2103287839-1384″‘) do (
IF errorlevel 0 if not errorlevel 1 call :mapl
)
exit /b 0
:: subroutines below
:mapo
net use O: /delete /y >NUL
net use O: \\myserver\myshare0 >NUL
exit /b 0
:mapl
net use L: /delete /y >NUL
net use L: \\myserver\myshare1 >NUL
exit /b 0