0

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???

1

1 Answer 1

0

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:

if not errorlevel 1 ...

or use delayed expansion. You can read up about that in help set.

Sign up to request clarification or add additional context in comments.

2 Comments

Some developers at MS must have been quite high on dope when they designed this, but your answer is correct...thanks a lot
It's been designed ages ago and had some strict compatibility requirements, I guess. Also keep in mind that the command line was more or less a second-class citizen on Windows until PowerShell.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.