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.
set "group=!%%G"
should beset "group=%%G"
- stray!
!if !ERRORLEVEL! equ 0 (
toIf Not ErrorLevel 1 (
.