DazedAndConfused
DazedAndConfused

Reputation: 1

Why isn't ERRORLEVEL giving the correct value in my batch file

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.

Upvotes: 0

Views: 61

Answers (1)

Squashman
Squashman

Reputation: 14290

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
 )

Upvotes: 0

Related Questions