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

  • possible duplicate of [Why does this batch variable never change even when set?](http://stackoverflow.com/questions/3949978/why-does-this-batch-variable-never-change-even-when-set) – Harry Johnston Nov 23 '14 at 22:53

1 Answers1

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.

Joey
  • 344,408
  • 85
  • 689
  • 683
  • Some developers at MS must have been quite high on dope when they designed this, but your answer is correct...thanks a lot – Juul Vanparijs Nov 23 '14 at 22:24
  • 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. – Joey Nov 24 '14 at 06:59