0

I'm trying to force the user to run the script using administrative privileges:

@echo off
net session >nul 2>&1
if %errorlevel% == 0 (
    echo Success: Administrative permissions confirmed.
    echo.
    echo Please Choose:
    echo 1. Enable
    echo 2. Disable
    echo 3. Exit

    set /p choice="> "
    echo Choice: "%choice%"
) else (
    echo Failure: Please run as administrator
)
pause

The net session and errorlevel lines check the privilege, and this works. The weird thing is that no matter what gets entered for choice it behaves as if it was never initialized.

The code running inside the if block works fine by itself, so I suspect the issue has something to do with how I'm checking for privileges.

Can someone explain this behavior, and any fixes?

  • 1
    your `set /p` works fine. It's the `echo` that fails because the echoed [variable is empty](https://stackoverflow.com/a/30284028/2152082) – Stephan Apr 05 '18 at 11:13
  • 1
    Possible duplicate of [Variables in batch not behaving as expected](https://stackoverflow.com/questions/30282784/variables-in-batch-not-behaving-as-expected) – aschipfl Apr 05 '18 at 12:54

2 Answers2

0

You'd need either delayed expansion or avoid it by reorganizing your code a bit, like:

@echo off
net session >nul 2>&1
if %errorlevel% == 1 (
  echo Failure: Please run as administrator
  exit 1
)
echo Success: Administrative permissions confirmed.
etc.
Stephan
  • 53,940
  • 10
  • 58
  • 91
0

The issue is because you are setting a variable within an If block, without delaying variable expansion.

However, you don't need the if block at all, nor do you need to set a variable for the selection.

The following method uses the || which essentially means 'if previous command produced an error', replaces the Set /P command with Choice and uses timed pauses via the Timeout command:

@Echo Off
Net Session >Nul 2>&1 || (
    Echo Failure: Please run as administrator
    Timeout 3 /NoBreak >Nul
    Exit /B
)
Echo Success: Administrative permissions confirmed.
Echo=
Echo 1. Enable
Echo 2. Disable
Echo 3. Exit
Choice /C 123 /M "Please Choose"
If ErrorLevel 3 Exit /B
If ErrorLevel 2 GoTo Disable
Echo Enabling
Timeout 3 /NoBreak >Nul
Exit /B
:Disable
Echo Disabling
Timeout 3 /NoBreak >Nul
Exit /B
Compo
  • 36,585
  • 5
  • 27
  • 39