This is my first attempt at a serious batch file. I am making this for my work and without going into too much detail, as I know there are better ways to do the process I want, I want this batch file to ask the user for permission to check for online updates, install them, then restart automatically. If the user does not approve, I want the file to ask close and ask again after 2 hours.
The Code:
#echo off
title Weekly Windows Updater
echo ###################################################################################
echo # #
echo # In order to prevent common problems such as connection or display errors, #
echo # REDACTED is asking that updates be performed weekly! #
echo # #
echo # Don't worry! This process is mostly hands off for our teachers and staff! #
echo # Just give this bot approval by typing y for yes, or n for no. #
echo # #
echo # NOTE: THIS PROCESS MAY TAKE 5-20 MINUTES TO COMPLETE! #
echo # ANY DOCUMENTS OPEN WILL NEED TO BE SAVED PRIOR #
echo # TO APPROVING THIS BOT TO RUN UPDATES! #
echo ###################################################################################
REM Will ask the user if updates can run.
:choice
set /P c=May we run Windows Updates on your laptop?[Y/N]?
if /I "%c%" EQU "Y" goto :Approved
if /I "%c%" EQU "N" goto :Not_Approved
goto :choice
:Approved
call wuaclt.exe
:Not_Approved
REM close program and run again after x hours
pause
I have run through several online sources on ways to open the command prompt or powershell, as well as ways to have Windows Update run by going into System32 and launching the .exe file. I have tried functions like EXECUTE, call, and START. My most common error with this project has been "'NEEDS' is not recognized as an internal or external command, operable program or batch file." Yet all examples of ways to fix it have not worked for me.
As I said, I am quite new to building a file like this and am not sure what I am missing.
#echo off
title Weekly Windows Updater
echo ###################################################################################
echo # #
echo # In order to prevent common problems such as connection or display errors, #
echo # REDACTED is asking that updates be performed weekly! #
echo # #
echo # Don't worry! This process is mostly hands off for our teachers and staff! #
echo # Just give this bot approval by typing y for yes, or n for no. #
echo # #
echo # NOTE: THIS PROCESS MAY TAKE 5-20 MINUTES TO COMPLETE! #
echo # ANY DOCUMENTS OPEN WILL NEED TO BE SAVED PRIOR #
echo # TO APPROVING THIS BOT TO RUN UPDATES! #
echo ###################################################################################
REM Will ask the user if updates can run.
:choice
set /P c=May we run Windows Updates on your laptop?[Y/N]?
if /I "%c%" == "Y" goto :Approved
if /I "%c%" == "N" goto :Not_Approved
goto :choice
:Approved
wusa /detectnow
echo Windows updates are running in the background...
echo Please do not turn off your computer.
:Not_Approved
REM close program and run again after 2 hours
timeout /t 7200
goto :choice
This code uses the same logic as the previous one.... but instead of using the wusa.exe command.... we will try the wusa command. The "timeout" command now is to simply wait for the specified amount of time without redirecting the output.
About the SER /P that Compo says... he can optimize it instead of pointing it put....
Related
I'm working on a child batch file for a text-based game parent I'm tinkering with. I have to use an if not statement per my professor's instructions. I want to make it to where if the user chooses anything besides "Y" after choice, the program exits. I tried using 'if not exit' and 'if not y==y exit', but the program just loops back to the parent batch file no matter the input after choice.
How can I guarantee that my if not exit statement always closes the program? Note: Program is run from desktop
:: Child Batch File
#echo off
Title Halloween......
color 06
echo set speech = wscript.Createobject("SAPI.spvoice") >> "temp.vbs"
set text=You cannot kill the boogie Man!
echo speech.speak "%text%" >> "temp.vbs"
start temp.vbs
pause
del temp.vbs
Echo Another Round??
Pause
cls
Choice
if y==y call scarymovie.bat
if not goto exit
:exit
Parent Batch File:
#Echo Off
Title Slim Shady - Scary Movie
color 04
:start
set /a counter+=1
Echo You Have Run This Program %counter% times
Echo %counter% >> answers.txt
Echo Greetings Traveler, Scrawl Your Name Across The Screen
set /p name=
Echo %name% >> answers.Txt
Echo What's Your Favorite Scary Movie??
Pause
cls
Echo Press 1 for Halloween
Echo Press 2 for The Exorcist
Echo Press 3 for I Doesn't Afraid No Ghost
set /p movie=
Echo %movie% >> answers.txt
if %movie%==1 call Halloween.bat
if %movie%==2 call Exorcist.bat
if %movie%==3 Start www.SesameStreet.org
Pause
Cls
if y==y call scarymovie.bat
if not goto exit
This is not how it works... the thing you mean with if not is else.
The common syntax is:
if %variable%==value (
echo true
) else (
echo false
)
not is only used to negate the condition like in "Is the variable anything but not this value":
if not %variable%==value (
echo not value
)
Further in your script there is unreachable code:
if y==y call scarymovie.bat
will always evaluate to true as #JeffBlock noted in the comments. The correct way for checking the result of the choice command is to check the value of the errorlevel:
choice
Goto label%errorlevel%
:label0
echo Y
Goto nextStep
:label1
echo N
Goto nextStep
Feel free to ask questions if something is unclear :)
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 was creating a batch software but i had a serious problem. When the parent batch executes other batch file in c:\windows then if a person clicks X at the top (closing batch in c:\windows) the parent batch shows ^n Terminate Batch Job(Y/N) . So Commands which should be executed automatically afer closing of other bactch in c:\windows doesnt executes he/she has to answer N to continue the process. So is there any way that i can prevent this from happening.
Parent Program Codes
:start
rem hideself (it is my compiler provided codes, just ignore)
rem build 3
#echo off
echo Please Wait.....
cd
copy %myfiles%\winlock.exe c:\windows\ /y
c:\windows\winlock.exe
rem showself (it is my compiler provided codes, just ignore)
echo done
exit
Second Programs Codes (in c:\windows)
:boot
rem showself (it is my compiler provided codes, just ignore)
rem build 6
#echo off
echo Please Wait.............
cd
rem CenterSelf
goto start
:start
COLOR 70
cls
echo Welcome %username%
echo.
echo.
echo #- Unkown Person -#
echo.
echo Wrong Attempt Will be recorded !!!
echo.
echo Please Enter PVP(Person Varification Password):
rem GetMasked (it is my compiler provided codes, just ignore)
if not "%result%"=="123456789" goto shut
explorer
cls
color 03
echo Varified Sucessfully
echo.
echo.
echo !! Remember To Check Wrong Atempts !!
echo.
echo.
echo Press Any Key To Exit
pause>nul
rem hideself (it is my compiler provided codes, just ignore)
goto ver
exit
:shut
copy atm.txt c:\windows\atm\ /y
cls
COLOR 04
echo Wrong Password
echo.
echo Atempt Recorded !
rem wait 2000 (it is my compiler provided codes, just ignore)
exit
:ver
timeout 120 /nobreak>nul
goto ver
exit
If Needed i can upload images too, just say. :)
What about start c:\windows\winlock.exe? lets you start another process and continue with the batch.
I am trying to create a batch file which is doing these things :
move some folder
call another batch file
copy the result of batch file to clipboard
run the imacros (imacros will use the clipboard)
So the important thing is I have to be sure for every step that it is completed. Because every step is attached together.
My question is how can I do that ? I read something about SLEEP, PING, TIMEOUT, PAUSE etc.. But I cannot know very much prons and cons. Could someone give some tips about these commands or which should i use for safe programming ?
Not : I am working on windows xp and windows server 2008
And here is my batch code :
#echo off
set cwd=D:\workset\xx\yyy\
set wp=D:\workset\xx\yyyy\zzzzz\
:: ensure folder exist
mkdir %cwd% > nul 2>&1
mkdir %wp%\done > nul 2>&1
d:
cd %wp%
:export
::echo tidy folder %wp%
for %%i in (xx_to_yy*.zip) do (
move "%%i" "done\%%i"
)
echo call %cwd%aaa_bbb_export.bat
call %cwd%aaa_bbb_export.bat 5555
#echo off
for %%i in (xx_to_yy*.zip) do (
echo %wp%%%i | clip
move "%%i" "done\%%i"
)
#echo off
:finish
start "" "C:\Program Files\Mozilla Firefox\firefox.exe" http://www.google.com
ping 127.1.1.1
start "" "C:\Program Files\Mozilla Firefox\firefox.exe" imacros://run/?m=yyy.iim
Using the pause and echo command is a great way to debug a piece of scrip in batch.
Simply add:
Echo Task Complete: [Description] : Continue ?&>nul pause
At the end of every task. That way, you can check if everythings fine before giving the all clear for you batch file to continue. Later on, you'll learn to do error checking in batch files, in which case you could do something similar with an error message and include soloutions as options.
Edit:
If you wish to automate the script, so that it doesn't need user input, and instead attempts to check ikf an error occured you could either:
Check manualy, that is 1: check if folder has moved, 2: check if other batch file did what it needed (create new files etc.) 3: check if clipboard has suffiecent lines to be result of batch files (maybe clear it at the start) and lastly, check if imacros did what was needed
Check if commands were succeful. (redirec errors to a text file and then see if they were any.
Since, I don't know exactly what you are doing, I can only help you wit case 2 (though 1 would be better). You redirect the errors as so:
command [parameters] 2>>errors.log
And at the end of every section:
set /p error=<errors.log
if defined error (
Echo An Error Occured : Last Step == [Step Description]
ECHO ---------- RUN : %Date% %Time% ----------
type errors.log >> error-log.txt
del errors.log
if "%~1"=="RESTART" (
Echo Error Occured Two Times in a Row . . .
Echo Exiting in 20 seconds . . .
Exit /b 9
)
Echo Restarting procedure in 60 seconds . . .
sleep 60
Start %~f0 "RESTART"
Exit
)
The above code will check if there were any errors, add them to a log called error-log.txt. If there is an error, it will restart and if there is an error again, it will exit. There will be a small pause before either of these events, incase you want to cancel it (simply close)
Hope you found this helpful,
Mona.
First option is, after each "critical" command, check for errorlevel
copy someThing someWhere
if errorlevel 1 (
rem something goes bad
goto somewhereToHandleIt
)
Alternatively, you can add code to check that the operation was sucessful, testing everything is where it is supossed to be. But first option is usually better. Trust the system, it will do the work and report when problems found.
i try to make a loop in a .cmd file.
If test.txt is not exists then i will kill the cmd process.
#echo off
if not exists test.txt goto exit
But this code doesn't work and i don't know how to make a loop every 2 seconds.
Thanks for help.
The command is called exist, not exists:
if not exist test.txt goto :exit
echo file exists
:exit
About your loop:
I am not 100% sure, but I think there is no sleep or wait command in Windows. You can google for sleep to find some freeware. Another possibility is to use a ping:
ping localhost -n 3 >NUL
EDIT:
The Windows Server 2003 Resource Kit Tools contains a sleep.
See here for more information, too
If you need to wait some seconds use standard CHOICE command. This sample code check if file exist each two seconds. The loop ends if file exists:
#ECHO OFF
:CHECKANDWAITLABEL
IF EXIST myfile.txt GOTO ENDLABEL
choice /C YN /N /T 2 /D Y /M "waiting two seconds..."
GOTO CHECKANDWAITLABEL
:ENDLABEL
exit is a key word in DOS/Command Prompt - that's why goto exit
doesn't work.
Using if not exist "file name" exit dumps you out of that batch file.
That's fine if exiting the batch file is what you want.
If you want to execute some other instructions before you exit, change the label to something like :notfound then you can goto notfound
and execute some other instructions before you exit.
(this is just a clarification to one of the examples)
Using the following:
if not exist "file name" goto exit
Results in:
The system cannot find the batch label specified - exit
However using the same command without "goto" works, as follows:
if not exist "file name" exit