0

I am trying to write a batch file that will test all local groups and report if a user belongs to the group.

Here is my code:

echo off
setlocal enabledelayedexpansion
for /f "tokens=*" %%G in ('net localgroup') do (
    set "group=!%%G"

    REM Process only real group names
    if "!group:~0,1!"=="*" (
        set group=!group:~1!

        REM Check if the user is in the group
        net localgroup "!group!" | find /i "!user!"
        if !ERRORLEVEL! equ 0 (
            echo !user! belongs to group !group!
        )
    )
)

The trouble is that ERRORLEVEL always returns 1 regardless of whether the user is in the group or not.

I am really at a loss to know what to try. I have tried web searching the behaviour of ERRORLEVEL in a pipe, or in a for loop, since I guess that is where the problem lies, but I've struggled to find an answer that helps.

3
  • 2
    You never assign a value to the variable user.
    – Squashman
    Commented Jul 1 at 16:23
  • 3
    set "group=!%%G" should be set "group=%%G" - stray !!
    – Magoo
    Commented Jul 1 at 16:23
  • 2
    Other than fixing the above mentioned typo, you could change if !ERRORLEVEL! equ 0 ( to If Not ErrorLevel 1 (.
    – Compo
    Commented Jul 1 at 17:36

1 Answer 1

0

You obviously have some typographical errors in your code. Not to mention missing code. But, your code could be as simple as this.

@echo off
set /p "_user=Enter name of user:"
for /f "tokens=1 delims=*" %%G in ('net localgroup ^| findstr /L "*"') do (
      net localgroup "%%~G" | find /i "%_user%" > nul 2>&1 && echo %_user% belongs to group %%~G
 )

Not the answer you're looking for? Browse other questions tagged or ask your own question.