E. Watson
E. Watson

Reputation: 13

Set /P not capturing input in IF statement

Everything in this batch script works fine, but when I enter the IF statement, for some reason set /p id= doesn't actually capture anything. In fact shortly after it will echo:

You chose session %id%.

but that will return a blank, as though nothing was entered for ID.

Any advice would be greatly appreciated.

@echo off

echo Please be sure CMD is being run as an administrator.

echo.

:loop

set /p targetpc="Which PC would you like to query for users (Hostname or IP)?: "

echo.

echo Querying %targetpc%...

echo.

quser /server:%targetpc%
echo.

set /p choice="Would you like to log a user off of %targetpc%? [Y/N]: "

echo.

IF /I "%choice%" EQU "Y" (

    echo Enter user's session ID:
    set /p id=
    echo.
    echo You chose session %id%.
    echo.
    logoff %id% /server:%targetpc% /V
    echo.
    echo Done!
    echo.
    goto loop
)

IF  /I "%choice%" EQU "N" (

    goto loop
)

Upvotes: 1

Views: 78

Answers (1)

Jason Faulkner
Jason Faulkner

Reputation: 6568

You are using the %id% value within the same block where it is set. This being the case, you need to use delayed expansion.

Add these lines to the top and bottom of your script, respectively:

SETLOCAL EnableDelayedExpansion

<Your script>

ENDLOCAL

Now use delayed expansion notation with your block (! around variables instead of %):

IF /I "%choice%" EQU "Y" (

    echo Enter user's session ID:
    set /p id=
    echo.
    echo You chose session !id!.
    echo.
    logoff !id! /server:%targetpc% /V
    echo.
    REM Note, replacing with a period here.
    echo Done.
    echo.
    goto loop
)

There are tons of other questions on this site regarding delayed expansion, so a quick search within the tag should yield lots of additional info if you need it.

Upvotes: 2

Related Questions