I am writing a batch file that continually pings a website in a simple :a goto a loop until a key is pressed . Is there a command that would accept simple 1 key input during the loop?
Five answers:
AnalProgrammer
2012-01-18 04:14:11 UTC
SET /P input=Please type a value:
To test the value of input use
%input%
This will however stop the program on every loop and may not be what you want.
Have fun.
?
2016-10-01 06:10:50 UTC
Windows Batch For Loop
Jake
2012-01-18 05:02:36 UTC
This is what you are looking for. It will loop until the Q button is pressed. Where it says "choice /c qc /t 1 /d c >nul" is where you would change the q to be any other button. the "/t 1" means it will wait one second for a user to respond, and then ping again. The only reason the /d c is in there is because it must default to a value other than q. I put "qc" to mean q -quit, c -continue.
echo off
setlocal enabledelayedexpansion
for /l %%a in () do (
cls
ping -n 1 www.go.com
choice /c qc /t 1 /d c >nul
if "!errorlevel!"=="1" exit
)
If you really want to use the goto, than this will do the exact same thing:
echo off
:loop
cls
ping -n 1 www.go.com
choice /c qc /t 1 /d c >nul
if "%errorlevel%"=="1" exit
goto loop
the "for" loop I put in there is an infinite loop - like i said...does the same thing.
husoski
2012-01-17 21:36:45 UTC
Nope. Not in standard Windows (CMD.EXE). You could:
1. Get one of the enhanced CMD.EXE replacement shells.
2. Install Cygwin and use a bash shell script instead.
3. Learn Windows Script Host (uses a VB-like macro language, by default).
4. Write a small C/C++ program to test for keyboard input and return the result as an ERRORLEVEL.
Any of those might work. I'd choose #4, but I'm a dinosaur. Something like the following will work with MS compilers, or with the MinGW port of GNU C/C++:
#include /* Nonstandard header -- windows/dos only */
int main (int argc, char**argv)
{
if (!kbhit()) return 0;
int key = getch();
if (key != (key & 0xFF)) key = 0xFF;
/*
... Can insert code here to test for an argument and return 1-based
... index of (key) in the argument. This could simplify ERRORLEVEL testing.
... For now, just return ASCII code as ERRORLEVEL.
*/
return key;
}
?
2012-01-17 21:38:20 UTC
A loop is well... A loop and cant be stoped in the manner you are talking about.
ping XXXXXX.com -t
will endlessly ping the site until you press CTRL+C
ⓘ
This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.