I was wondering if there was a command to automatically exit a batch file if it is left alone for a certain number of seconds.
I made a little program similar to the one found here. Most of the coding I used is displayed on the page, but it basically asks you what website you want to visit, and selecting one of the options opens a browser window with the desired page. however, after selecting one of the listed sites, the program displays the options to either exit or return to the top. This is where I usually forget about it until I close whatever I was looking at, and the batch is still open in the background.
So is there anyway to set a auto-exit timer without it interrupting the user, and without restricting the ability to go back and select another option?
Thanks!
You can use choice command, instead set /p
Where z is an automatic option, you can use another letter.
/D is the default option if time is passed.
/T is the time to wait (this case, 5 seconds).
choice /n /c:zbe /T 5 /D x /M "Make your selection"
Then use it on your code:
choice /n /c:xbe /T 5 /D x /M "Make your selection"
if errorlevel 1 exit
if errorlevel 2 goto :option_b
if errorlevel 3 goto :option_e
More info type in cmd:
choice /?
Please take a look here
set /p udefine=
this line is waiting for b or e
Since you only want to exit the batch file after selecting one website, you can just wipe these lines
echo Type [e] to exit or [b] to go back and select another site.
echo.
set /p udefine=
echo.
echo ***************************************************************
if %udefine%==b goto top
if %udefine%==e goto exit
:exit
cls
echo ***************************************************************
and also this line (before the last one)
pause
Related
I am trying to make a batch file that will continuously check if a certain PDF is open, if not than it opens said PDF file.
I am new to batch file programming but have been able to create a batch file with "start" that opens the specific PDF. After doing some research I believe a for loop with use of a task-list might be able to get me what I need but do not really know how to implement it.
start AcroRd32.exe "C:\Users\user1\Documents\Folder1\PDF Forms\App.pdf "
Any help would be appreciated!
UNTESTED
This might work for you. I think it will fail if the pdf is read only to the user.
WARNING Be very careful typing or copying type nul>>"%filename%". If you mess it up you can erase the contents of the file. It must be double >>. A single > will erase the contents.
set "fname=C:\Users\user1\Documents\Folder1\PDF Forms\App.pdf"
:infiniteloop
:: Check if the file is accessible, goto openfile if it is
(type nul>>"%fname%" && goto :openfile) >nul 2>nul
:: 1 second delay so the loop doesn't go crazy
timeout /t 1 >nul
goto :infiniteloop
:openfile
start AcroRd32.exe "%fname%"
:: Give it time to open before checking again
:: I chose 30 seconds
timeout /t 30>nul
goto :infiniteloop
This depends on the file being "locked" or whatever by the program that has it open. On my computer, Adobe Reader does "lock" a PDF file, but Microsoft Edge does not.
You do not need a for loop for this it would just create an extra process which is not needed.
#echo off
:start
tasklist /FI "WINDOWTITLE eq App.pdf" | find /i "AcroRd32.exe"
if errorlevel 1 start AcroRd32.exe "C:\Users\user1\Documents\Folder1\PDF Forms\App.pdf"
timeout /t 10 >nul 2>&1
goto :start
What I want is a command (or series of commands) that works with Windows 7, 8.1, and 10. It needs to collect user input at any time during the execution of the batch file it's in, only to checked and interpreted later. I do not mind using an input text file.
I've already searched for an answer, but the closest I've come to it is <nul set /p "input=", but it requires the user to press a key and hit enter at the exact moment the command is run. Any help would be greatly appreciated.
This method utilizes GOTO to create a loop which checks the first line of input.txt every 6 seconds or so. You could replace the content of :DOSTUFF with anything you want. Let me know if you have questions.
#echo off
GOTO DOSTUFF
:CHECKINPUT
for /f %%a in (input.txt) do (
if %%a NEQ "" (
set "input=%%a"
GOTO GOTINPUT
)
exit /b
)
GOTO DOSTUFF
:GOTINPUT
echo Thanks for the input!
echo Here is what you entered:
echo %input%
GOTO ENDER
:DOSTUFF
echo I could be doing other things here, but instead I'm just waiting for input...
PING 127.0.0.1 -n 6 >nul
GOTO CHECKINPUT
:ENDER
pause
While this was running in one window, I just ran echo test>input.txt in another command prompt.
To make this more robust you might want to overwrite the file after you check it. This can easily be done with echo.>input.txt
I think I have what I want (described below), thank you so much again, but please two more options... When I want to add in sub menu two next options for example "B" like go on Begin and "E" like Exit. It will be like:
Hello I am Zedd, please choose one app bellow:
Notepad
Calc
Other
When I touch "3" like other I will get next menu:
FFox
IE
or B. Go Back
or E. Exit
How can I do this? And can I use just number 0-9 or I can use also 10,11 etc.?
Examople of code maybe like this?
#echo off
:begin
echo.
echo Hello, I'm Zedd...
echo.
echo Choose:
echo.
echo 1. Notepad
echo 2. Calc
echo 3. Other
echo.
choice /c 123
if %errorlevel%==1 goto :Notepad
if %errorlevel%==2 goto :Calc
if %errorlevel%==3 goto :Other
:Notepad
start notepad.exe
goto :eof
:Calc
start calc.exe
goto :eof
:Other
echo.
echo Choose:
echo.
echo 1. FFox
echo 2. IE
echo 3 or B. Back
echo 4 or E. Exit
echo.
choice /c 1234(maybe 12be if I can use also b and e, or I can use 3,4... is possible here use 10,11,12 etc.?)
if %errorlevel%==1 "C:\Program Files (x86)\Mozilla Firefox\firefox.exe"
if %errorlevel%==2 "C:\Program Files\Internet Explorer\iexplore.exe"
if %errorlevel%==3 goto :begin?
if %errorlevel%==4 exit?
goto :other (I want to stay in other for choosing next apps but I want to be able to go back or exit)
Also, can I do it with note, so when I choose FFox there will be message "You choosed FFox" etc.?
Hope I described it clearly, if you can help me, I will be happy, thank you!
Could you please advise me on how to write commands in CMD using a batch file that would include different options and actions?
I've researched a nice description of the functions I can use, but I'm not able to put together them functionally.
Here's an example of the output message that I want when my batch file runs on Windows:
I need to do batch, for example "test.bat"
I think this is the easiest way. In this batch I want to have some text and some choices. For example bellow:
Hello, I am Zedd, here is few options for you, please choose one.
1. Run notepad.exe
2. Other apps
After entering number 1, Notepad is opened. After entering number 2, more options should be displayed:
1. Firefox
2. More informations
etc.
I need to run this batch file on Windows.
What is best way how to do this?
It can be full-screen or just within a window.
Also I need open apps or pictures, etc.
(Edited to show the usage of a second level of choices)
just a combination of echo and choice commands:
#echo off
:begin
echo Hello, I am Zedd, here is few options for you, please choose one.
echo 1. Run notepad.exe
echo 2. Other apps
choice /c 12
if %errorlevel%==1 goto :notepad
if %errorlevel%==2 goto :other
:notepad
echo you choosed Notepad.
start notepad.exe
goto :eof
:other
echo 1. Mozilla Firefox
echo 2. Microsoft Internet Explorer
echo 3. MyBatchFile
echo B. back to main menue
echo E. exit
choice /c 123B
if %errorlevel%==1 "C:\Program Files (x86)\Mozilla Firefox\firefox.exe"
if %errorlevel%==2 "C:\Program Files\Internet Explorer\iexplore.exe"
if %errorlevel%==3 (
echo you choosed MyBatchFile
call "c:\test\mybatch.bat"
goto :begin
)
if %errorlevel%==4 (
echo you entered "B" to go back to main menue
goto :begin
)
if %errorlevel%==5 (
echo bye bye...
exit /b
)
goto :other
You can add the /n parameter to choice to supress [1,2]?
EDIT 02-sep (please don't change your question, this may invalidate already existing answers; ask a new question instead, referencing this old question)
"How can I do this? And can I use just number 0-9 or I can use also 10,11 etc.?"
No. choice reacts on keypresses, not on input strings, so only single numbers or letters. Although 3 or B. Back is possible: choice /c 123b4e will return errorlevel 1 for 1, 2 for 2, 3 for 3, 4 for b or B, 5 for 4, 6 for e or E. (read choice /? for details). Then
...
if %errorlevel%==3 goto :back REM this was a "3"
if %errorlevel%==4 goto :back REM this was a "B"
...
"Also, can I do it with note, so when I choose FFox there will be message "You choosed FFox" etc.?"
Yes. Just add an echo after each label (see example above with the :notepad label.
Yes, it could be possible to do that in plain batch commands. I would suggest, though, use a language like C++ or C, to do that...but if you must use batch, here are a lot of commands that you can play with.
My question is how would I make a batch script instead of closing when the X in the top right is pressed to execute a file called exit.exe.
There are a couple points in this question that are not clear enough:
If you want that when the rigth top X is pressed on the cmd.exe window it not close, but do a different thing instead, then there is no way to achieve such thing with any existent window, that is, with the windows of all existent applications.
If you want to differentiate if the window that execute your Batch file terminated normally or terminated because the user click on the right top X, then the way to achieve that is via a previous "starter" program that execute your Batch file and expects a certain value returned from it. If the returned value is not the expected one, then it is assumed that the window was cancelled via the right top X.
starter.bat:
#echo off
echo Start yourScript.bat:
start "" /W yourScript.bat
echo Value returned from the script: %errorlevel%
if %errorlevel% neq 12345 ECHO execute exit.exe
yourScript.bat:
#echo off
echo I am the script.bat
set /P var=input value:
rem Terminate normally:
exit 12345
the [X] is "out of reach" for cmd. Only way, I can think of is: create another cmd to watch the presence of the current window:
#echo off
title WatchMe
more +7 %~f0 >t2.bat
start "watcher" t2.bat
exit /b
#echo off
:running
tasklist /v|find "WatchMe" >nul &&echo waiting || goto finished
timeout 1 >nul
goto running
:finished
echo "the process has finished
I have a batch file that automates copying a bunch of files from one place to the other and back for me. Only thing is as much as it helps me I keep accidentally selecting that command off my command buffer and mass overwriting uncommitted changes.
What code would I need for my .bat file to make it output "Are you sure?", and make me type Y before it ran the rest of the file?
If anything other than Y is typed, it should exit execution on that line.
When I call exit, it closes cmd.exe which is not what I want.
You want something like:
#echo off
setlocal
:PROMPT
SET /P AREYOUSURE=Are you sure (Y/[N])?
IF /I "%AREYOUSURE%" NEQ "Y" GOTO END
echo ... rest of file ...
:END
endlocal
try the CHOICE command, e.g.
CHOICE /C YNC /M "Press Y for Yes, N for No or C for Cancel."
There are two commands available for user prompts on Windows command line:
set with option /P available on all Windows NT versions with enabled command extensions and
choice.exe available by default on Windows Vista and later Windows versions for PC users and on Windows Server 2003 and later server versions of Windows.
set is an internal command of Windows command processor cmd.exe. The option /P to prompt a user for a string is available only with enabled command extensions which are enabled by default as otherwise nearly no batch file would work anymore nowadays.
choice.exe is a separate console application (external command) located in %SystemRoot%\System32. File choice.exe of Windows Server 2003 can be copied into directory %SystemRoot%\System32 on a Windows XP machine for usage on Windows XP like many other commands not available by default on Windows XP, but available by default on Windows Server 2003.
It is best practice to favor usage of CHOICE over usage of SET /P because of the following reasons:
CHOICE accepts only keys (respectively characters read from STDIN) specified after option /C (and Ctrl+C and Ctrl+Break) and outputs an error beep if the user presses a wrong key.
CHOICE does not require pressing any other key than one of the acceptable ones. CHOICE exits immediately once an acceptable key is pressed while SET /P requires that the user finishes input with RETURN or ENTER.
It is possible with CHOICE to define a default option and a timeout to automatically continue with default option after some seconds without waiting for the user.
The output is better on answering the prompt automatically from another batch file which calls the batch file with the prompt using something like echo Y | call PromptExample.bat on using CHOICE.
The evaluation of the user's choice is much easier with CHOICE because of CHOICE exits with a value according to pressed key (character) which is assigned to ERRORLEVEL which can be easily evaluated next.
The environment variable used on SET /P is not defined if the user hits just key RETURN or ENTER and it was not defined before prompting the user. The used environment variable on SETÂ /P command line keeps its current value if defined before and user presses just RETURN or ENTER.
The user has the freedom to enter anything on being prompted with SET /P including a string which results later in an exit of batch file execution by cmd because of a syntax error, or in execution of commands not included at all in the batch file on not good coded batch file. It needs some efforts to get SET /P secure against by mistake or intentionally wrong user input.
Here is a prompt example using preferred CHOICE and alternatively SET /P on choice.exe not available on used computer running Windows.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
echo This is an example for prompting a user.
echo/
if exist "%SystemRoot%\System32\choice.exe" goto UseChoice
setlocal EnableExtensions EnableDelayedExpansion
:UseSetPrompt
set "UserChoice="
set /P "UserChoice=Are you sure [Y/N]? "
set "UserChoice=!UserChoice: =!"
if /I "!UserChoice!" == "N" endlocal & goto :EOF
if /I not "!UserChoice!" == "Y" goto UseSetPrompt
endlocal
goto Continue
:UseChoice
%SystemRoot%\System32\choice.exe /C YN /N /M "Are you sure [Y/N]?"
if not errorlevel 1 goto UseChoice
if errorlevel 2 goto :EOF
:Continue
echo So you are sure. Okay, let's go ...
rem More commands can be added here.
endlocal
Note: This batch file uses command extensions which are not available on Windows 95/98/ME using command.com instead of cmd.exe as command interpreter.
The command line set "UserChoice=!UserChoice: =!" is added to make it possible to call this batch file with echo Y | call PromptExample.bat on Windows NT4/2000/XP and do not require the usage of echo Y| call PromptExample.bat. It deletes all spaces from string read from STDIN before running the two string comparisons.
echo Y | call PromptExample.bat results in YSPACE getting assigned to environment variable UserChoice. That would result on processing the prompt twice because of "Y " is neither case-insensitive equal "N" nor "Y" without deleting first all spaces. So UserChoice with YSPACE as value would result in running the prompt a second time with option N as defined as default in the batch file on second prompt execution which next results in an unexpected exit of batch file processing. Yes, secure usage of SET /P is really tricky, isn't it?
choice.exe exits with 0 in case of the user presses Ctrl+C or Ctrl+Break and answers next the question output by cmd.exe to terminate the batch job with N for NO. For that reason the condition if not errorlevel 1 goto UserChoice is added to prompt the user once again for a definite answer on the prompt by batch file code with Y or N. Thanks to dialer for the information about this possible special use case.
The first line below the batch label :UseSetPrompt could be written also as:
set "UserChoice=N"
In this case the user choice input is predefined with N which means the user can hit just RETURN or ENTER (or Ctrl+C or Ctrl+Break and next N) to use the default choice.
The prompt text is output by command SET as written in the batch file. So the prompt text should end usually with a space character. The command CHOICE removes from prompt text all trailing normal spaces and horizontal tabs and then adds itself a space to the prompt text. Therefore the prompt text of command CHOICE can be written without or with a space at end. That does not make a difference on displayed prompt text on execution.
The order of user prompt evaluation could be also changed completely as suggested by dialer.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
echo This is an example for prompting a user.
echo/
if exist "%SystemRoot%\System32\choice.exe" goto UseChoice
setlocal EnableExtensions EnableDelayedExpansion
:UseSetPrompt
set "UserChoice="
set /P "UserChoice=Are you sure [Y/N]? "
set "UserChoice=!UserChoice: =!"
if /I not "!UserChoice!" == "Y" endlocal & goto :EOF
endlocal
goto Continue
:UseChoice
%SystemRoot%\System32\choice.exe /C YN /N /M "Are you sure [Y/N]?"
if not errorlevel 2 if errorlevel 1 goto Continue
goto :EOF
:Continue
echo So you are sure. Okay, let's go ...
endlocal
This code results in continuation of batch file processing below the batch label :Continue if the user pressed definitely key Y. In all other cases the code for N is executed resulting in an exit of batch file processing with this code independent on user pressed really that key, or entered something different intentionally or by mistake, or pressed Ctrl+C or Ctrl+Break and decided next on prompt output by cmd not terminating the batch job.
For even more details on usage of SET /P and CHOICE for prompting user for a choice from a list of options see answer on How to stop Windows command interpreter from quitting batch file execution on an incorrect user input?
Some more hints:
IF compares the two strings left and right of the comparison operator with including the double quotes. So case-insensitive compared is not the value of UserChoice with N and Y, but the value of UserChoice surrounded by " with "N" and "Y".
The IF comparison operators EQU and NEQ are designed primary for comparing two integers in range -2147483648 to 2147483647 and not for comparing two strings. EQU and NEQ work also for string comparisons, but result on comparing strings in double quotes after a useless attempt to convert left string to an integer. EQU and NEQ can be used only with enabled command extensions. The comparison operators for string comparisons are == and not ... == which work even with disabled command extensions as even command.com of MS-DOS and Windows 95/98/ME supported them. For more details on IF comparison operators see Symbol equivalent to NEQ, LSS, GTR, etc. in Windows batch files.
The command goto :EOF requires enabled command extensions to really exit batch file processing. For more details see Where does GOTO :EOF return to?
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
choice /?
echo /?
endlocal /?
goto /?
if /?
set /?
setlocal /?
See also:
This answer for details about the commands SETLOCAL and ENDLOCAL.
Why is no string output with 'echo %var%' after using 'set var = text' on command line?
It explains the reason for using syntax set "variable=value" on assigning a string to an environment variable.
Single line with multiple commands using Windows batch file for details on if errorlevel X behavior and operator &.
Microsoft documentation for using command redirection operators explaining the redirection operator | and handle STDIN.
Wikipedia article about Windows Environment Variables for an explanation of SystemRoot.
DosTips forum topic ECHO. FAILS to give text or blank line - Instead use ECHO/
The choice command is not available everywhere. With newer Windows versions, the set command has the /p option you can get user input
SET /P variable=[promptString]
see set /? for more info
Here a bit easier:
#echo off
set /p var=Are You Sure?[Y/N]:
if %var%== Y goto ...
if not %var%== Y exit
or
#echo off
echo Are You Sure?[Y/N]
choice /c YN
if %errorlevel%==1 goto yes
if %errorlevel%==2 goto no
:yes
echo yes
goto :EOF
:no
echo no
Here's my go-to method for a yes/no answer.
It's case-insensitive also.
This just checks for the errors given by the input and sets the choice variable to whatever you require so it can be used below in the code.
#echo off
choice /M "[Opt 1] Do you want to continue [Yes/No]"
if errorlevel 255 (
echo Error
) else if errorlevel 2 (
set "YourChoice=will not"
) else if errorlevel 1 (
set "YourChoice=will"
) else if errorlevel 0 (
goto :EOF
)
echo %YourChoice%
pause
You can also use 'Choice' command
#echo off
echo Sure?
CHOICE /C YN
IF %ERRORLEVEL% EQU 1 goto CONTINUE
IF %ERRORLEVEL% EQU 2 goto END
:END
exit
:CONTINUE
echo hi
pause
If you want to the batch program to exit back to the prompt and not close the prompt (A.K.A cmd.exe) you can use "exit /b".
This may help.
set /p _sure="Are you sure?"
::The underscore is used to ensure that "sure" is not an enviroment
::varible
if /I NOT "_sure"=="y" (
::the /I makes it so you can
exit /b
) else (
::Any other modifications...
)
Or if you don't want to use as many lines...
Set /p _sure="Are you sure?"
if /I NOT "_sure"=="y" exit /b
::Any other modifications and commands.
Hope this helps...
Here is a simple example which I use in a backup (.bat / batch) script on Windows 10, which allows me to have different options when making backups.
...
:choice
set /P c=Do you want to rsync the archives to someHost[Y/N]?
if /I "%c%" EQU "Y" goto :syncthefiles
if /I "%c%" EQU "N" goto :doonotsyncthefiles
goto :choice
:syncthefiles
echo rsync files to somewhere ...
bash -c "rsync -vaz /mnt/d/Archive/Backup/ user#host:/home/user/Backup/blabla/"
echo done
:doonotsyncthefiles
echo Backup Complete!
...
You can have as many as you need of these blocks.
You can consider using a UI confirmation.
With yesnopopup.bat
#echo off
for /f "tokens=* delims=" %%# in ('yesnopopup.bat') do (
set "result=%%#"
)
if /i result==no (
echo user rejected the script
exit /b 1
)
echo continue
rem --- other commands --
the user will see the following and depending on the choice the script will continue:
with absolutely the same script you can use also iexpYNbutton.bat which will produce similar popup.
With buttons.bat you can try the following script:
#echo off
for /f "tokens=* delims=" %%# in ('buttons.bat "Yep!" "Nope!" ') do (
set "result=%%#"
)
if /i result==2 (
echo user rejected the script
exit /b 1
)
echo continue
rem --- other commands --
and the user will see:
I would do it in the following way to make sure the testing and variables are correct during looping etc..
:: rem at the top of the script
setlocal enabledelayedexpansion
:: choice example
CHOICE /C YNC /M "Continue? Press Y for Yes, N for No or C for Cancel."
If /I "[!errorlevel!]" NEQ "[1]" ( GOTO START_OVER )
There are so many answers, but none of them seems to be simple and straight forward. This is the code I am using:
choice /M "Do you want to continue?"
if %errorlevel% EQU 1 (
... run your code lines here
)
First, open the terminal.
Then, type
cd ~
touch .sure
chmod 700 .sure
Next, open .sure and paste this inside.
#!/bin/bash --init-file
PS1='> '
alias y='
$1
exit
'
alias n='Taskkill /IM %Terminal% /f'
echo ''
echo 'Are you sure? Answer y or n.'
echo ''
After that, close the file.
~/.sure ; ENTER COMMAND HERE
This will give you a prompt of are you sure before continuing the command.
Open terminal. Type the following
echo>sure.sh
chmod 700 sure.sh
Paste this inside sure.sh
#!\bin\bash
echo -n 'Are you sure? [Y/n] '
read yn
if [ "$yn" = "n" ]; then
exit 1
fi
exit 0
Close sure.sh and type this in terminal.
alias sure='~/sure&&'
Now, if you type sure before typing the command it will give you an are you sure prompt before continuing the command.
Hope this is helpful!