Set /P not capturing input in IF statement - batch-file

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
)

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 batch-file tag should yield lots of additional info if you need it.

Related

trying to make an "OS" in batch

#echo off
:load
rem imitation of loading the os
color 70
ver
title boot
echo please wait...
ping localhost -n 3 >nul
cls
systeminfo
rem in here user types name he wants to be his account name
:login
title login
cls
date
cls
echo welcome to windows 71
echo before we bigen please type your name
set /P_name=here:
if %name%=admin goto admin
if not goto ms
rem ms=menu start
:ms
echo %time%
echo hello %name%
echo type HELP for list to commands
set /P_command=here:
if %command%=help goto help
if %command%=exit goto exit
if %command%=calendar goto cal
if not goto wc
rem wc=wrong command
:admin
echo hello %name% to the admin panel
echo type HELP for list to commands
set /P_command=here:
if %command%=help goto help
if %command%=exit goto exit
if %command%=calendar goto cal
So the problem is that it crashes after the :LOGIN part and I don't know what to do!
I'm trying to make an OS batch (something like MS-DOS), but it crashes after the "login" part.
I tried everything I could think of and it didn't work, also I want to make a save file so users can set a password for their "account".
As mentioned in above comments, you need to correctly use your variables, you can however use choice instead of set /p for your commands.
#echo off
:load
rem imitation of loading the os
color 70
ver
title boot
echo please wait...
timeout /t 3 >nul
cls
systeminfo
rem in here user types name he wants to be his account name
:login
title login
cls
date /t
timeout /t 2>nul
cls
echo welcome to windows 71
echo Before we begin please type your name
set /P "_name=here:"
if /i "_%name%"=="admin" goto admin
rem ms=menu start
:ms
echo %time%
echo hello %_name%
echo type HELP for list to commands
CHOICE /C HEC /M "Press H for Help, E to exit C for Calender."
goto opt%errorlevel%
:admin
echo hello %_name% to the admin panel
echo type HELP for list to commands
CHOICE /C HEC /M "Press H for Help, E to exit C for Calender."
goto opt%errorlevel%
:opt1
echo Help stuff goes here
goto :eof
:opt2
exit
:opt3
echo Calenders stuff goes here
Some things to note. You do not require to goto ms is the user is not admin as the statement for not being admin will not be met, we will automatically faal through into the ms label.
Notice where the problems were in your code. i.e if %name%=admin should be if "%_name%"=="admin" with double equal sign and the underscore in the name. It is also double quoted to ensure that we do a match without unwanted whitespace. Lastly /I option to catch ADMIN in any case.
See if /?, choice /? from command line for more help around these functions.
Okay this code is quite wrong.
I fixed it.
#echo off
:load
rem imitation of loading the os
color 70
title boot
echo please wait...
ping localhost -n 3 >nul
cls
rem in here user types name he wants to be his account name
:login
title login
cls
echo Welcome to Microsoft Windows 7!
echo Before we begin, please type your name.
set /p name=here:
if "%name%"=="admin" goto admin
if not "%name%"=="admin" goto ms
rem ms=menu start
:ms
echo %time%
echo Hello %name%
echo Type HELP for list to commands
set /p command=here:
if "%command%"=="help" goto help
if "%command%"=="exit" goto exit
if "%command%"=="calendar" goto cal
goto ms
rem wc=wrong command
:admin
CLS
echo hello %name% to the admin panel
echo type HELP for list to commands
set /P command=here:
if "%command%"=="help" goto help
if "%command%"=="exit" goto exit
if "%command%"=="calendar" goto cal
GOTO :ADMIN
Okay but you don't need to start systeminfo and all that.

SET /p crashing batch file process

In a batch file I'm getting information from the user for later database work.
I first ask if the user is using Windows Auth and then depending on the answer, I ask for username & password, or set a variable and continue on.
But for the life of me, I can't figure out why one of the SET /p lines is causing the batch file to crash, when another SET /p line isn't.
Here's my code:
#ECHO OFF
#SETLOCAL ENABLEDELAYEDEXPANSION
CHOICE /M "Will you be using Windows Authentication to connect to the database?"
ECHO ERRORLEVEL: %ERRORLEVEL%
#PAUSE
IF ERRORLEVEL 2 (
ECHO ERRORLEVEL should be 2: %ERRORLEVEL%
#PAUSE
SET _USINGWINAUTH=FALSE
SET /p _USERNAME=User name:
REM SET /p _PASSWORD=Password (NOTE: Password will be displayed as you type):
) ELSE (
ECHO ERRORLEVEL should be 1: %ERRORLEVEL%
#PAUSE
SET _USINGWINAUTH=TRUE
)
ECHO.
ECHO _USINGWINAUTH: %_USINGWINAUTH%
ECHO _USERNAME: %_USERNAME%
ECHO _PASSWORD: %_PASSWORD%
#PAUSE
As is, with the second SET /p commented out, regardless if you answer Y or N the script runs fine.
But if the second SET /p line is not commented, regardless of what the answer is, the script instantly closes right after hitting a key at the pause before the ECHO ERRORLEVEL.
I just don't see why that's happening!
As per last time, whilst using a caret works, it would be better if you were to rework the logic.
One example:
#ECHO OFF
CHOICE /M "Will you be using Windows Authentication to connect to the database"
IF "%ERRORLEVEL%"=="1" SET "_USINGWINAUTH=TRUE" & GOTO NEXT
SET "_USINGWINAUTH=FALSE"
SET /P "_USERNAME=User Name: "
SET /P "_PASSWORD=Password (will be displayed as you type): "
:NEXT
ECHO(
SET _USINGWINAUTH
SET _USERNAME 2>NUL
SET _PASSWORD 2>NUL
PAUSE

How do I create an update function in Batch?

I would like to create an update function that works just after the user is prompted to type into the "ChatBox" so that other users on my school network can type and all other users can see it without having to restart the program or typing space to reload the .txt file
here is the code I have written so far;
:enter
cls
type cblog.txt
echo.
set /p text=
echo %text% >> cblog.txt
goto enter
I like this topic, so I wrote a fully working prototype:
#echo off
setlocal
if "%~1" equ "" echo You must give your username as parameter & goto :EOF
set "user=%~1"
set "now=%time%"
echo %now%: User %user% entered the chat room>> msgQueue.txt
call :chatRoom 3< msgQueue.txt
goto :EOF
:chatRoom
rem Omit previous messages
:omitMsg
set /P "msg=" <&3
if "%msg:~0,12%" neq "%now%:" goto omitMsg
echo %msg%
echo/
echo Press S to send a message or eXit to end
echo/
:msgLoop
rem Check for new messages received
:showMsg
set "msg="
set /P "msg=" <&3
if not defined msg goto send
echo %msg%
goto :showMsg
rem Check to send a new message
:send
ver > NUL
choice /C SNX /N /T 3 /D N > NUL
if errorlevel 3 goto end
if errorlevel 2 goto msgLoop
rem Send a message
echo -----------------------------------
set /P "msg=Message: "
echo -----------------------------------
echo %user%: %msg% >> msgQueue.txt
goto msgLoop
:end
echo %time%: User %user% leaved the chat room>> msgQueue.txt
The response time may be adjusted in /T 3 parameter of choice command: shorter times makes the chat more responsive, but it consume more CPU time.
Below is an image that show a test with four users in the Chat Room:

Making a batch file do something once

I'm making a game and I want a personalized username option that only appears once.
Here is an example:
#echo off
:onetime
echo please enter a username
echo.
set /p newuser=%newuser%:
echo %newuser%> cfg.txt
goto menu
:menu
for /f "tokens=* delims=" %%x in (cfg.txt) do echo %%x
cls
...
I'm trying to figure out how to make :onetime happen once, so that it sends the username to cfg.txt
Anyone know how?
I have cleaned up your code and provided a completed working script, and noted where you will put your game code.
Although Delayed expansion is not needed for this code, I have placed it in the script as you had it in your original script.
Please be mindful of the variable names I have chosen as they are used in several locations.
I have tried to comment the code with info on what it is doing, and I would be happen to explain further if needed.
I'd like to actually play your game when you are completed with it, if I may. :)
Hope that helps.
Ben
BPG.cmd
REM Script: BPG.cmd
REM Version: 1.0
REM Description: Game to play about Monsters.
Rem Notes: Currently Implementing Menu System.
Rem Sets up Variables and checks if the script needs to be re-called.
#(
SETLOCAL ENABLEDelayedExpansion
echo off
SET "eLvl=0"
SET "ScriptFolder=%~dp0"
SET "Log=%~dpn0.log"
SET "ConfigFile=%~dpn0_cfg.txt"
IF /I "%~1" NEQ "MAX" (
ENDLOCAL
ECHO.Game not started Maximized, Opening in a New Window by Running: Start "BPG 1 A Batch of Monsters" /MAX "%~dpnx0" MAX
Start "BPG 1 A Batch of Monsters" /MAX "%~dpnx0" MAX
EXIT /b %eLvl%
)
COLOR 2
)
REM Calls Main Function.
CALL :Main
REM Ends the script.
(
ENDLOCAL
EXIT /b %eLvl%
)
REM Main Function, most of your coding goes here, and this function calls sub functions.
:Main
Rem Check if Config file exists, if it does not, then call the New User Function.
IF NOT EXIST "%ConfigFile%" (
CALL :NewUser
)
Rem Load Username from Config file.
FOR /F "Tokens=*" %%A IN ('Type "%ConfigFile%"') DO (
SET "_UserName=%%~A"
)
Rem Call Menu System
CALL :Menu
REM Based off the option chosen Either Start a new Game or Skip to the End.
REM ECHO.CALL %_Menu_Choice%
CALL %_Menu_Choice%
GOTO :EOF
:NewUser
SETLOCAL
REM Get the Username Input
SET /P "_User=Please Enter a Username: "
REM Output the Username to the config file, overwriting all the file contents:
echo.%_User%>"%ConfigFile%"
ENDLOCAL
GOTO :EOF
:Menu
SETLOCAL
REM Output the Config file contents:
Type "%ConfigFile%"
REM Clear the screen
cls
echo ______ _______ _______
echo I ___ \ I ____ I I ____ \
echo I I I II I II I I \/
echo I I__/ / I I____II I I
echo I __ I I _____I I I ____
echo I I \ \ I I I I \_ I
echo I I___I II I I I___I I
echo I______/ I_/ I_______I A BATCH OF MONSTERS
echo.
echo.
echo 1) Begin
echo.
echo 2) Exit
echo.
set /p "_Choice=%_UserName%, Enter a Number: "
(
REM End the local variable Space, and Set return variables based on the choice, or re-draw the menu.
ENDLOCAL
IF /I "%_Choice%" EQU "1" (
REM ECHO.%_Choice% EQU 1
SET "_Menu_Choice=:Begin_Game"
) ELSE (
IF /I "%_Choice%" EQU "2" (
REM ECHO.%_Choice% EQU 2
SET "_Menu_Choice=GOTO :EOF"
) ELSE (
ECHO.%_Choice% Not Valid!
PAUSE
GOTO :Menu
)
)
)
goto :EOF
:Begin_Game
REM All the remaining code for your game should probably go here.
GOTO :EOF
try checking file existence :
#echo off
:onetime
setlocal enableDelayedExpansion
if not exist "cfg.txt" (
echo please enter a username
echo.
set /p newuser=%newuser%:
echo !newuser!> cfg.txt
goto menu
)
:menu
for /f "tokens=* delims=" %%x in (cfg.txt) do echo %%x
cls

net group /add /domain alternative batch file windows xp

First post here, I'm trying to create a batch file that allows a technician to supply a text file with computer names and add them to a security group. I've written the following script that uses NET GROUP, net group /domain works, but I can't use net group %filepath% /add /domain. The environment I'm under is Windows XP. Please help! Cheers.
#echo off
title ModGroup
echo Discovering available groups on %USERDOMAIN%, please wait...
echo.
net group /domain > grouplist_.txt
set /p entgrpname=Type whole group name:
findstr /i "%entgrpname%" grouplist_.txt > tmp2_.txt
(
set /p var=
)<tmp2_.txt
del tmp2_.txt
del grouplist_.txt
set var="%var:~1%"
echo.
rem ****%var% is the group name the user specified and its been verified to exist****
msg "%username%" WARNING! - You are about to edit the %var% group! - Please take extra caution whilst using this script!
echo.
echo Please enter the full filepath of the *.txt file that contains objects that you
echo want to add/remove.
echo.
set /p filepath=Filepath:
echo.
(
set /p filepath2=
)<%filepath%
echo.
set /p addrem=Please specify if you would like to add or delete:
cls
echo You're about to %addrem% the following objects to/from %var%:
echo.
echo %filepath2%
echo.
pause
echo.
echo Processing, please wait...
echo.
for /F "tokens=1 delims=" %%i in (%filepath%) do net group %var%
%%i /%addrem% /domain
echo.
pause
exit

Resources