Comparing User input variable to time command in batch - batch-file

I'm trying to make a batch file that'll run in the background and shut my computer off when the regional time corresponds to a time I've set so that I can fix my sleep schedule.
However, I'm running into issues testing how to compare the current time to the time I've set as a variable.
I believe that it's due to the format that is returned by the time command and the format I entered not being the same.
I would like to enter a time in the 12-hour format and the computer shuts down at the designated time. But the time command returns a 24-hour format string unless paired with the /t switch.
This is what I currently have as test code that returns a printed line instead of shutting down my computer:
#echo off
set /p shutdownTime=What time would you like to shut down the computer?
:begin
set time=time /t
if "%time%" EQU "%shutdowmTime%" echo Time Confirmed
goto begin
I know that instead of an if statement in a loop I could probably do a for or while loop, but I'm honestly trying to keep it as simple as I can for my nocturnal smooth brain that woke up about 3 hours ago.
Any help is appreciated. Thank you.

Try this:
#echo off
FOR /F "tokens=* USEBACKQ" %%F IN (`time /t`) DO (
SET var=%%F
)
echo %var%
pause
will output 12hr time
#echo off
:resettime
echo make sure to Use caps for AM/PM and no spaces
set /p stime=What time would you like me to shutdown your computer?[example 03:45(AM/PM)]:
cls
echo your computer will shutdown at %stime%
:R
set /p p=would you like to change this time [y/n]:
if %p%==y goto resettime
if %p%==n goto loop
if not %p%==y goto R
if not %p%==n goto R
:loop
FOR /F "tokens=* USEBACKQ" %%F IN (`time /t`) DO (
SET var=%%F
)
set var=%var: =%
if %stime%==%var% goto endloop
goto loop
:endloop
shutdown /s
:a
set /p prompt=Would you like to abort shutdown [y/n]:
if %prompt%==y goto s
if not %prompt%==y goto a
:s
shutdown /a
I also quickly made the program described in your question. Its a bit buggy but it works.

Related

Batch file asks infinite times for input

#echo off
:cancel
shutdown /a
:shut
set a=%1
shutdown -s -f -t %a%
cls
set /p a="the computer will shut in:" %=%
set /a a=%a%*60
if %a%=="a" call :cancel
pasue
call :shut
pause
It is supposed to ask the user for a number. It will take the number and shutdown the computer in x minutes (I Multiplied by 60 to convert to seconds), if the answer is "a" it will cancel the shutdown.
When I start the program, it is asking me infinity times for input and doesn't call shutdown at all
Thanks :)
Looking at your code, I guess, you're confusing "labels" with "Function declarations". There are no functions in batch (at least not like in other languages), just call, goto and "labels"
For the shown task, you don't need any labels at all:
#echo off
set /p a="the computer will shut in:" %=%
if /i "%a%"=="a" shutdown -a & goto :eof
set /a a*=60
shutdown -s -f -t %a%
(Note: you had a logical failure in your code: set /a always returns an Integer (as long as it doesn't produce a syntax error), so it doesn't make sense to compare the variable with the string a after the set /a)
Recommended read: Where does GOTO :EOF return to?
Try this:
::It's better to comment out #echo off, and only when the .bat works fine and then use it.
::#echo off
cls
set /p a="the computer will shut in:"
::You'll need to put %a% inside quotes too, otherwise it can't be equal when you input a.
if "%a%"=="a" call :cancel & goto :eof
:: equals to set /a a=a*60, and with /a you don't need %
set /a a*=60
:: You forgot the parameter. And the goto :eof is necessary
call :shut %a%
pause && goto :eof
::You need to put functions at last.
:cancel
shutdown /a
goto :eof
:shut
set a=%1
shutdown -s -f -t %a%
The main problem in your code is the execution flow.
When there's no switch or gotos, it will execute commands from first line to the last line.
(That's why it asked you infinite times, because every time you call :cancel, it will execute from :cancel function to the set /p again.)
You need to put functions below the main codes.
And in the functions, you need to add goto :eof(except the last line since it's alreay end of file).
And after the function calls you need add goto :eof too.

Loop the command continuously (without pausing) for "X" seconds

Currently I am working on a batch file to execute a command continuously for X no. of seconds, and after elapse of X, I wish to redirect it using goto function.
This is the closest I have got to what I intend the code to do.
:MainMenu
set yourno=
set /p yourno=Input your number:
set /p looptime=Input time:
goto PerformCalc
:PerformCalc
set /a yourno= %yourno%+1
timeout 1
set /a looptime=%looptime%-1
goto CheckLoop
:CheckLoop
if %looptime% equ 0 goto FinishScreen
goto PerformCalc
:FinishScreen
echo Congratulations Your no. is %yourno%
echo Operations completed in %looptime% seconds
pause
Now the problem with the above code is if I set the loop time for 10 seconds, it will perform only 10 operations. But that is not something I intend to do. I realize that I have inputted timeout 1 in my code and reducing it by 1 everytime 1 second passes. However this is because I am unable to find a way to continuously loop the code for 10 seconds, without using timeout 1 thus pausing it to perform only 10 operations.
If you still do not get what I mean, here is the logical flow the code should perform (say for eg. the user inputs looptime as 10 seconds
For Time=10seconds
Do {set /a yourno= %yourno%+1 continuously}
After Time of 10 seconds has elapsed redirect to :FinishScreen
Thankyou for your help.
#echo off
setlocal
rem Get end time
set seconds=10
for /F "tokens=1-4 delims=:.," %%a in ("%time: =0%") do set /A "endTime=1%%a%%b%%c%%d+seconds*100"
echo Start: %time%
echo Working %seconds% seconds, please wait...
set yourNo=0
:loop
set /A yourNo+=1
rem Check if end time had been reached
for /F "tokens=1-4 delims=:.," %%a in ("%time: =0%") do if 1%%a%%b%%c%%d lss %endTime% goto loop
echo End: %time%
echo This program could complete %yourNo% loops in 10 seconds
This method may fail if the processing time pass over midnight, but a simple adjustment can solve this point, if needed...

Batch - How To Run Two Commands At The Same Time?

I think someone asked a similar questions ,but mine is a bit different. I have this code:
#echo off
title Game
set time=1 am
timeout 10 /nobreak >nul & goto game
set time=2 am
:game
How can I make the
timeout 5 /nobreak >nul
and
goto game
work at the same time? This is how I want it to work if you still didn't get it:
The timeout starts and you play the game after the timeout ends it changes the time to 2 am. How can I do that at the same time and play the game without getting disturbed? Please help. Thanks!
No, Bob. 'tis you who doesn't get the point about the variable time. It is a reserved variable which is set by the system, but can be overridden by a user script. Virtually any other variable name, you can use - just not time, date, path, random and a few others.
As to your problem,
set "mytime=1 am"
call :starttimer
:game
... whatever
:getinput
set "response="
set /p "response=%~1"
if not exist timerfinished.txt goto :eof
:: here change "mytime"
set "mytime=2 am"
:starttimer
start /min "" timer.bat 10
goto :eof
where timer.bat is
#echo off
del timerfinished.txt 2>nul
timeout %1 /nobreak>nul
echo.>timerfinished.txt
exit
The timer.bat file simply deletes the flag-file timerfinished.txt, delays for the time set by the first parameter it receives (%1 - set to 10 in main code) then creates the file and exits.
The main code starts the timer initially using :starttimer then whenever you want to prompt-and-wait-for-a-response, you execute
call :getinput "Prompt for input "
and the response will appear in %response%.
Note that setting response to nothing initially in this routine ensures that the response is empty if the user simply presses Enter
OK - so nothing actually happens using this scheme until you enter a response, only then will the time be incremented and the game continues with an updated time. If you're expecting that the end of the timeout actually does something, really - that's not going to happen - unless you use choice to input your responses with the timeout option.
i think you are looking for a "game time", running faster than real time.
Best way: use another script to set a gametime variable (like below) in a separate (minimized) window. Whenever you need to access the current "gametime" in your main script, use <gametime.dat set /p "gametime="
GAMETIME.BAT:
#echo off
set gametime=10:00
for /f "tokens=1,2 delims=:" %%a in ("%gametime%") do (
set hours=%%a
set mins=%%b
)
:loop
call :increase_gametime
timeout 5 >nul
goto :loop
:increase_gametime
set /a mins+=10
set /a hours=hours+mins/60
set /a mins=mins%%60
set gametime=%hours%:%mins%
title %gametime%
>gametime.dat echo %hours%:%mins%

I need to press a specific key and have my script " GO TO" another part in the script

I have a batch script that I desperately need help with. I use a batch script to grab files from folders and move them. The script sweeps the folders every 30 sec but you can "press a key to continue" also. I need to change it so I can press a specific key, doesn't matter what key, and have it GO TO the top location of my script to reset.
Below is a striped down version of what I currently have.
#echo off
set /p username=ENTER LOGIN:
echo.
:pc
echo 1 -- Flats
echo 2 -- Simple Tabletop
set /P rmFunc="Enter a choice: "
for %%I in (1 x) do if #%rmFunc%==#%%I goto run%%I
:run1
set pc=300
goto begin
:run2
set pc=400
goto begin
:begin
set studio=TT
set computer=Handbag_1
set setnumber=
set studiosetnumber=%studio%_%setnumber%
set delay_swch=5
set delay_loop=30
:bottom
echo logged in as: %username%
timeout /t %delay_loop%
GOTO BOTTOM
It is not possible to determine what key was pressed when using TIMEOUT, so that command is of no help.
You could use the CHOICE command with the /T (timeout) and /D (default) options instead. You can no longer simply press any key. Instead you can only press one key to restart, and another specific key to continue, or wait till the default value (continue) is returned. The biggest drawback is it no longer has a visual countdown.
echo Press C to Continue, or R to Restart
choice /c cr /d c /t 30 /n /m "The process will automatically continue in 30 seconds "
if errorlevel 2 goto pc
goto bottom
You could display a countdown timer by adding a third undocumented default option and setting the timeout to 1 second. If the default is returned, then it decrements the counter. Once the counter reaches 0 then the desired time has elapsed and you treat it as Continue.
I use the SET /P trick to display the prompt with a without a newline. I end with a carriage return so that the next prompt displays from the beginning of the same line.
The countdown timing will be a bit off, but it should be plenty good enough.
The carriage return variable must be defined and delayed expansion must be enabled near the top (before any loop label).
:: Define CR to hold a carriage return (0x0D)
for /f %%A in ('copy /Z "%~dpf0" nul') do set "CR=%%A"
:: Delayed expansion must be enabled to use the CR variable
setlocal enableDelayedExpansion
The timer code then becomes
set wait=15
:waitLoop
<nul set /p ="Press C to Continue, or R to Restart. Auto continue in %wait% seconds. !CR!"
choice /c 0cr /t 1 /d 0 >nul
if errorlevel 3 echo(&goto pc
if errorlevel 2 echo(&goto bottom
set /a wait-=1
if %wait% equ 0 echo(&goto bottom
goto :waitLoop
timeout does not return errorlevel if interrupted, so perhaps one way to solve this is to time timeout
#ECHO Off
SETLOCAL
SET /a "starttime=1%time:~-5,2%%time:~-2%"
timeout /t 30
SET /a "endtime=1%time:~-5,2%%time:~-2%"
IF %endtime% lss %starttime% SET /a endtime +=6000
SET /a elapsed=endtime - starttime
ECHO %elapsed%
GOTO :EOF
elapsed should contain the resultant time in tens-of-milliseconds. It's unlikely to be exactly 3000 for a 'no keypress' situation, but perhaps if %elapsed% gtr 2980 echo no keypress would suffice.
Note that I use a time format of hh:mm:ss.hh so if yours is different, you'd need to adjust the time substringing.
Since the target here is a timeout of about 30 seconds, the calculations can be performed on the seconds digits only. The values are accumulated as 1ss(.)hh which ensures that there is not a leading zero so set /a will not attempt to enter octal mode. Since it's entirely possible that the end time will be in the next minute, the adding of 6000 compensates by adding-in the minute (6000 tens-of-milliseconds)
Since it seems to be necessary to build the entire batch,
#echo off
set /p username=ENTER LOGIN:
echo.
:pc
echo 1 -- Flats
echo 2 -- Simple Tabletop
set /P rmFunc="Enter a choice: "
:
for %%I in (1 x) do if #%rmFunc%==#%%I goto run%%I
:run1
set pc=300
goto begin
:run2
set pc=400
goto begin
:begin
set studio=TT
set computer=Handbag_1
set setnumber=
set studiosetnumber=%studio%_%setnumber%
set delay_swch=5
set delay_loop=30
:bottom
echo logged in as: %username%
SET /a "starttime=1%time:~-5,2%%time:~-2%"
timeout /t %delay_loop%
SET /a "endtime=1%time:~-5,2%%time:~-2%"
IF %endtime% lss %starttime% SET /a endtime +=6000
SET /a elapsed=endtime - starttime
if %elapsed% leq 2980 goto ???
GOTO BOTTOM
And - well there I'd have to leave it. You are setting studio and setnumber to constants within your code. Are these somehow related to "Process Class?" If you want to re-enter this data, then you'd need ??? above to be begin - but you'd need to set /p those values (which you haven't shown.) As for the file sweep - there's nowhere in your code that shows this filesweep happening. The modifications I have indicated will allow you to press any key to interrupt the 30-second bottom loop and re-enter the data.

Batch Making Passwords

I have made a batch game where users can log in / register. But there is no point in having passwords if a person standing nearby can peep at the password. Normal password fields mask the characters with asterisks (*).
How can mask characters on a batch file?
I've seen this done on cmd before but I have no clue how.
You can use XCOPY for a hidden input, it can handle nearly all characters and you can also implement a backspace logic.
#echo off
setlocal EnableDelayedExpansion
call :input
echo(
echo '!input!'
if "!input!"=="password" echo OK
exit /b
:input
for /F "tokens=1 delims=# " %%a in ('"prompt #$H# & echo on & for %%b in (1) do rem"') do (
set "\b=%%a"
)
set "input="
:keyLoop
call :GetKey
if not defined key exit /b
if "!key!"=="!\b!" (
if defined input (
set "input=!input:~0,-1!"
<nul set /p ".=!\b! !\b!"
)
) ELSE (
<nul set /p ".=*"
set "input=!input!!key!"
)
goto :keyLoop
:GetKey
setlocal DisableDelayedExpansion
set "key="
for /F "usebackq delims=" %%L in (`xcopy /L /w "%~f0" "%~f0" 2^>NUL`) do (
if not defined key set "key=%%L"
)
(
endlocal
set "key=^%key:~-1%" !
exit /b
)
This code should be able to handle all characters, like ^!&%<>.
It's also possible to use backspace to delete the last entered character.
The line set "key=^%key:~-1%" ! seems odd, but it's used to escape the ! character with set "key=^!" ! in the delayed expansion context.
And to avoid problems for all other characters the last ! removes the caret, like in set "key=^A" ! will be evaluated to ``set "key=A"`
Ok, this is a bit different to what you may have had in mind, but that's you're fault for choosing batch for game dev.
The way I see it is you have 3 options:
Use an external program you self made in C#, C++, Python, [etc.]
Howver this requires an application to already do this for you (Which there probably is) or for you to have a knowledge in one of these languages
Use the choice command, to continuously take one key input and wait for the user to hit space to signify the end of the password
However this limits the password characters choice, and makes the program look ugly
Use 2 Batch threads, one that masks and tallies input while the other stores it to a variable.
This may be a bit dodgey at times, at would be a bit complicated but may be the only choice you have.
Now, as I was typing this an idea stuck my head on how to achieve this. Since it might take some time to test I thought I'd post the idea (as it seems to be a soloution to this problem, which has been around for a while).
Logic
One Batch Thread will simply use set /p to store all the input into a variable and upon completion will communicate to the other batch thread through the use of waitfor or a simple directory file.
Another Batch Thread would loop the pause >nul statement and would tally the number of times the pause statement is looped, printing out the appropriate amount of *'s. The other important job of this thread is to sense when the user has finished typing the password, upon which it exits.
Im starting to make this batch program now, but for now I'll just keep you informed of my idea so far.
Code
Login.bat
#echo off
Title Password Please:
:: This is the main code
REM This code relies on Masker.bat
REM SET password to be first and thrid letter,
REM of the day of the week.
set pass=%Date:~0,1%%Date:~2,1%
REM START Masker in the same window using /b tag and create hold.pass:
Echo 0 >%temp%\hold.pass
start /b Masker.bat "%pass%" *
REM Simply take input an leave the rest to Masker.bat
set /p pass_input=:
Echo 1 >>%temp%\hold.pass
cls
if /i "%pass%" NEQ "%pass_input%" (
Title Worng Password
Echo Wrong Password... Sorry.
Sleep 5
Exit
)
Pause > nul
REM Rest of Main game code is below or simply
:: START Main.bat & Exit
Masker.bat
#echo off
Title Password Please:
setlocal enabledelayedexpansion
:: This is not the main code
REM This code is called upon by Login.bat (or the Main.bat game code)
REM CREATE the variables "passlen" and "mask":
set password=%~1
set passlen=0
:miniloop
set /a passlen+=1
if "!password:~%passlen%,1!" NEQ "" goto :miniloop
set password=
set mask=%~2
if "%mask%" EQU "" set mask=*
REM MAIN loop
:loop
cls
for /l %%a in (1,1,%passlen%) do (<nul set /p=%mask%)
sleep -m 150
for /f "usebackq" %%a in ("%temp%\hold.pass") do (if "%%~a" EQU "1" Del %temp%\hold.pass & Exit)
goto :loop
It still needs some more improvements, but I've spent aroung 30 min on it with little success to make it dynamically tell you how many characters you have typed in.
Anyone cane take this up, be my guest. Everything else works fine
Mona
This works without pressing enter after input of the password.
If you enter the correct password, ok.
if you enter a wrong password, it will stop when you enter the 9th character (can be adapted).
It does not care about capitalization.
Problem: the password is stored as pure text in the code
#echo off
setlocal enabledelayedexpansion
set "s= abcdefghijklmnopqrstuvwxyz"
set p=
:loop
choice /C %s% /N >nul
set p=%p%!s:~%errorlevel%,1!&set /p =*<nul
if /i "%p%"=="secured" goto :right
if not "%p:~8,1%"=="" goto :wrong
goto :loop
goto :wrong
:right
echo you entered correct password: %p%
goto :eof
:wrong
echo you entered wrong password: %p%
goto :eof
You may use ReadFormattedLine subroutine for all kind of formatted input. For example, the command below read a password of 8 characters, display asterisks in the screen, and continue automatically with no need to press Enter:
call :ReadFormattedLine password="********" /M "Enter password (8 chars): "
This subroutine is written in pure Batch so it does not require any additional program, and it allows several formatted input operations, like read just numbers, convert letters to uppercase, etc. You may download ReadFormattedLine subroutine from Read a line with specific format.

Resources