I'm trying to determine if a script runs with admin authorities on Win7, but errorlevel doesn't seem to get set consistently after executing a "net" command...
This is (simplified) my code:
net session >null 2>$1
if %errorLevel% == 0 (
echo This seems to be mighty ADMIN...
) else (
echo Poor sod... no Admin, no glory - errorLevel: %errorLevel%
)
@SETLOCAL
@set TSTHOME=%~dp0
@set TSTNAME=%~n0
set SAL=NO
set SCL=NO
:VAL_PARM
if .%1 == . @goto :VAL_PARM_END
if /i %1 == SAL (
net session >null 2>$1
if %errorLevel% == 0 (
set SAL=YES
) else (
echo Option "SAL" requires Administrator priviliges (run "as Admin" or from an elevated command prompt)
goto :EOF
)
) else (
if /i %1 == SCL (
set SCL=YES
) else (
echo off
echo Invalid argument "%1"; correct syntax: %TSTNAME% [SAL] [SCL]
echo where: SAL: save agent logs of each command
echo SCL: save client logs of each command
echo NOTE: "SAL" requires "Administrator" privileges
goto :EOF
)
)
shift
goto :VAL_PARM
:VAL_PARM_END
But when I run this from a regular command prompt, this is the output:
C:\MyDir>isAdmin sal
C:\MyDir>net session 1>null 2>$1
C:\MyDir>if 2 == 0 (echo This seems to be mighty ADMIN... ) else (echo Poor sod... no Admin, no glory - errorLevel: 2 )
Poor sod... no Admin, no glory - errorLevel: 2
C:MyDir>set SAL=NO
C:\MyDir>set SCL=NO
C:\MyDir>if .sal == .
C:\MyDir>if /I sal == SAL (
net session 1>null 2>$1
if 0 == 0 (set SAL=YES )
else (echo Option "SAL" requires Administrator priviliges (run "as Admin" or from an elevated command prompt )
goto :EOF
)
Why for heaven's sake is the second "net session" not setting errorLevel???
Don't compare errorlevels like that, as the variable will be expanded before the
if
block even executes and thus retains its value from before the block. Use the following instead:or use delayed expansion. You can read up about that in
help set
.