Network connection - batch file runs and adds my error message at end - batch-file

I'm having an issue when I run a batch file. When the script successfully connects to the internet and runs, the failed message is still coming up. When I intentionally fail the script, I get a "network error 53". How do I check for this? I did not see any information on errorlevels besides:
"if errorlevel 1 goto failed:" and then create a failed message
Script runs successfully: Error message stills come up after everything runs properly. Meaning..my "failed: " message still occurs.
Network connection fails: ":failed" part runs as it should
#echo off
cls
ping XXXXXXX
#echo off
net use o: \\XXXXXXXXX
if errorlevel 1 goto failed:
#echo on
ping XXXXXXXXX
killdisk.exe -XXXXXX -XXXX
:failed
echo Unable to access the network share. Please confirm your Ethernet connection and try again.
echo Please press a key to exit or the prompt will exit after 30 seconds.
PAUSE 30
echo EXITING

To facilitate a variety of possible use cases, the Windows Command Prompt doesn't stop executing when it reaches a label (i.e. :failed).
In order to stop execution before the label, you can put one of the following commands before your label:
EXIT - This command closes the command prompt. If you call other batch files or subroutines within your batch, this is not what you want. The EXIT command will close the command prompt window and stop processing everything.
GOTO:EOF - The GOTO command generally takes a label such as your :failed, but in this case :EOF is a special reserved label that tells the command prompt to skip to the end of the current batch file. This would then return control to the batch file that called this one.
Further reading:
Exit - SS64
Goto - SS64

Related

Combine Windows CMD BAT files

I'm trying to build a .bat file that will run an executable Java SpringBoot web app jar file (keeping the cmd window open so that I can verify it started cleanly and close it/kill the process when I'm done), then wait 10 seconds to give the app time to start, then finally open it's URL in my web browser.
I've been able to get my intended functionality by breaking it down into two .bat files. The code I have below does what I want (except the echo message is repeated, but that's not a big deal).
I'd like to know how I can achieve the same functionality within a single .bat file.
I have launch.bat:
start wait.bat
java -jar C:\dev_tools\myapp.jar
which calls wait.bat:
echo Waiting for app to start before launching browser...
timeout 10
start http://localhost:8013/myapp/ && exit
Given the combined script is called launch.bat, put if not "%~1" == "" goto :JUMP on top, then the contents of launch.bat but with the first line changed to start launch.bat #, then place goto :EOF, then :JUMP, then the contents of wait.bat:
if not "%~1" == "" goto :JUMP
start launch.bat #
java -jar C:\dev_tools\myapp.jar
goto :EOF
:JUMP
echo Waiting for app to start before launching browser...
timeout 10
start http://localhost:8013/myapp/ && exit
When you now start launch.bat, it first checks if there is an argument, which should not be the case initially; so the first start command line is reached where the script executes itself, but with an argument (#) this time; the initially executed instance continues executing the rest until goto :EOF is reached, which terminates execution.
The recursively called instance will immediately continue execution at label :JUMP, where the code of the original wait.bat script is placed.
I think, this should work:
#echo off
start "MyApp" java.exe -jar C:\dev_tools\myapp.jar
echo Waiting for app to start before launching browser...
%SystemRoot%\System32\timeout.exe 10
start http://localhost:8013/myapp/
java.exe is started as separate process running parallel to cmd.exe instance processing this batch file.
So immediately after starting java.exe the information line is output by cmd.exe in initially opened console window.
Then timeout is executed to wait 10 seconds before finally the application is started with the HTTP URL.
Finally cmd.exe finishes processing the batch file as reading end of batch file which results in terminating the cmd.exe if started with option /C as done on double clicking on a batch file.
The Java application started as separate process keeps running independent on termination of cmd.exe processing the batch file.
I hope this is what you want.
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.
echo /?
start /?
timeout /?

Why does command START used in a batch file not start a batch file?

I made a Main batch file with the lines below:
#echo off
color 1e
title ------ Just a Test ------
start "C:\Users\%USERNAME%\Desktop\Check.bat"
:START
echo Welcome to the Game!
...
And Check.bat contains:
#echo off
if not exist "C:\Users\%USERNAME%\Desktop\Batch_System\importantFile.dll" goto ERROR
if exist "C:\Users\%USERNAME%\Desktop\Batch_System\importantFile.dll" goto CONTINUE
:ERROR
cls
echo ERROR :
echo Important file not found. please reinstall the program
pause
exit /b
:CONTINUE
cls
exit /b
When I use the command start, it starts only a command prompt with the Check.bat directory and the main batch file continues executing the game. I want to force close the main batch file if importantFile.dll doesn't exist.
Okay, let me explain: When the main batch file is executed and runs the command start to start another batch file called Check.bat, the file Check.bat checks if the file importantFile.dll exists, and if not, Check.bat displays an error message.
Does anyone know how to write Check.bat in a manner that when the .dll file does not exist, force the main batch file to exit?
First, help on every command can be get by running in a command prompt window the command with /? as parameter. start /? outputs the help of command START. call /? outputs the help of command CALL usually used to run a batch file from within a batch file. Those two commands can be used to run a batch file as explained in detail in answer on How to call a batch file that is one level up from the current directory?
Second, the command line
start "C:\Users\%USERNAME%\Desktop\Check.bat"
starts a new command process in foreground with a console window with full qualified batch file name as window title displayed in title bar at top of the console window. That is obviously not wanted by you.
Third, the Wikipedia article Windows Environment Variables lists the predefined environment variables on Windows and their default values depending on version of Windows.
In general it is better to use "%USERPROFILE%\Desktop" instead of "C:\Users\%USERNAME%\Desktop".
There is no C:\Users on Windows prior Windows Vista and Windows Server 2008 by default at all.
The users profile directory can be on a different drive than drive C:.
It is also possible that just the current user's profile directory is not in C:\Users, for example on a Windows server on which many users can logon directly and for which the server administrator decided to have the users' profile directories on a different drive than system drive making backup and cleaning operations on server much easier and is also better for security.
Well, it is also possible to have the user's desktop folder not in the user's profile directory. But that is really, really uncommon.
Fourth, on shipping a set of batch files, it is recommended to use %~dp0 to call other batch files from within a batch file because of this string referencing drive and path of argument 0 expands to full path of currently executed batch file.
The batch file path referenced with %~dp0 always ends with a backslash. Therefore concatenate %~dp0 always without an additional backslash with another batch file name, folder or file name.
See also What is the reason for batch file path referenced with %~dp0 sometimes changes on changing directory?
Fifth, I suggest following for your two batch files:
Main.bat:
#echo off
color 1e
title ------ Just a Test ------
call "%~dp0Check.bat" || color && exit /B
echo Welcome to the Game!
Check.bat:
#echo off
cls
if exist "%~dp0Batch_System\importantFile.dll" exit /B 0
echo ERROR:
echo Important file not found. Please reinstall the program.
echo/
pause
exit /B 1
The batch file Check.bat is exited explicitly on important file existing with returning exit code 0 to the parent batch file Main.bat. For that reason Windows command processor continues execution of Main.bat on the command line below the command line calling the batch file Check.bat.
Otherwise Check.bat outputs an error message, waits for a pressed key by the user and exits explicitly with non zero exit code 1. The non zero exit code results in Main.bat in executing the next command after || which is COLOR to restore initial colors and next executing also EXIT with option /B to exit the execution of Main.bat.
See also:
Single line with multiple commands using Windows batch file
What are the ERRORLEVEL values set by internal cmd.exe commands?
Which cmd.exe internal commands clear the ERRORLEVEL to 0 upon success?
Where does GOTO :EOF return to?
exit /B without an additionally specified exit code is like goto :EOF.
The CALL command line in Main.bat could be also written as:
call "%~dp0Check.bat" || ( color & exit /B )
And Main.bat could be also written as:
#echo off
color 1e
title ------ Just a Test ------
call "%~dp0Check.bat"
if errorlevel 1 (
color
goto :EOF
)
echo Welcome to the Game!
I do not recommend using in Main.bat just EXIT instead of exit /B or goto :EOF. Just EXIT would result in exiting the current command process independent on calling hierarchy and independent on how the command process was started: with option /K to keep it running to see error messages like on opening a command prompt window and next running a batch file from within command prompt window, or with /C to close the command process after application/command/script execution finished like on double clicking on a batch file.
It is advisable to test batch files by running them from within an opened command prompt window instead of double clicking on them to see error messages on syntax errors output by cmd.exe. For that reason usage of just EXIT is counter-productive for a batch file in development. Run cmd /? in a command prompt window for help on Windows command processor itself.
Last but not least see:
Microsoft's command-line reference
SS64.com - A-Z index of the Windows CMD command line
start is asynchronous by default. Use start /wait so that main.bat can test the exit code of check.bat. Make check.bat return an appropriate exit code.
For example...
main.bat
#echo off
start /b /wait check.bat
if not %errorlevel% == 0 exit /b
echo "Welcome to the game!"
...
check.bat
#echo off
if exist "importantfile.dll" exit 0
echo ERROR: Important file not found. Please reinstall the program.
pause
exit 1
notes
Added /b to start to avoid opening another window. Change that per your preference.
You could use call instead of start but call gives the called code access to the variables of main.bat so encapsulation is improved if you use start as you did.
The logic in check.bat is simplified above. Once you identify the success path early in the script and exit, the rest of the script can assume the fail path. This saves you a few if's and labels which you might find simplifies writing and reading of similar scripts. Beware of potentially confusing multiple exit points in longer scripts though!
When choosing exit codes, 0 is a common convention for success.
The above code is just one technique - there are several other options (such as checksomething && dosomethingifok). Some useful information on return codes, and checking them, can be found in http://steve-jansen.github.io/guides/windows-batch-scripting/part-3-return-codes.html
Thanks to the answer from Mofi. I've my example and exp. on this. To be short, it's about the setting of log date format. You may change the format of time , date and log. you may have the result.
why-batch-file-run-with-failure-in-windows-server

Why can't get exit code of batch file executed with command start?

When I run command Start C:\temp\sub2.bat in a command prompt window, errorlevel set is 4 and this is correct because a file which is indicated in batch does not exist. But when I run through this below, errorlevel returns 0. I have no idea why the exit codes are different.
Can anyone give me an advice for the reason?
#echo off
Call :Sub1
GOTO :EOF
:Sub1
start C:\temp\sub2.bat
echo %errorLevel%
Read the answer on How to call a batch file that is one level up from the current directory? It explains the 4 methods which exist to run a batch file from within a batch file and what are the differences.
You use command start which results in starting a new command process running parallel to the command process already executing your batch file for execution of C:\temp\sub2.bat.
The current command process immediately continues the execution of posted batch file and evaluates the exit code of command start which is 0 on successfully starting the executable or batch file.
You should use the command call to run the batch file as subroutine in your batch file and which makes it possible to evaluate the exit code set by C:\temp\sub2.bat.
#echo off
call C:\temp\sub2.bat
if errorlevel 1 echo There was an error with exit code %ERRORLEVEL%.
It would be also possible to start the other batch file in a new command process and what on its termination for example with exit 4 in current batch file.
#echo off
start /wait C:\temp\sub2.bat
if errorlevel 1 echo There was an error with exit code %ERRORLEVEL%.
In general it is not advisable to use exit without option /B as this results always in exiting the command process independent on calling hierarchy which makes it also impossible to debug a batch file by running it from within a command prompt window.
In case of C:\temp\sub2.bat really contains exit ExitCode without option /B and for some unknown reason the batch file can't be edited, it is really necessary to start C:\temp\sub2.bat in a separate command process and wait for its termination with start /wait.
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.
call /?
echo /?
exit /?
if /?
start /?
Read also the Microsoft support article Testing for a Specific Error Level in Batch Files.
See also the Stack Overflow questions:
What are the ERRORLEVEL values set by internal cmd.exe commands?
Which cmd.exe internal commands clear the ERRORLEVEL to 0 upon success?

blocking an if statement error message from a batch file

I am trying to design a batch program that scans the D:\ on my computer for a CD album and then opens a program to play it. I don't want to use Autoplay because want to design my own custom program for the purpose. I am using an IF statement and a GOTO statement that loops back to the IF statement after a delay. Here is what I have:
:rescan
if exist D:\Track01.cda start (my soon-to-be music playing program)
timeout 2 /NOBREAK
goto rescan
The problem is that if there is no CD in the drive, the IF statement causes a seprate error message window to pop up.
Is there any way to block this message?
I do not think there is a way to block this message as it is occurring outside of the control of your batch file. However I checked the existence of the drive before entering the loop and this seemed to work for my tests.
IF EXIST D:\ GOTO rescan
echo Drive does not exist
goto end
:rescan
if exist D:\Track01.cda echo start (my soon-to-be music playing program)
timeout 6 /NOBREAK
goto rescan
:end
Hope it helps you out.
use another command:
dir D:\track01.cda 1>nul 2>&1 && start (your program)
If there is no disk, dir returns The device is not ready. and an %errorlevel%of 1. If there is a disk, but no audio-disk (no "track01.cda"), dir returns "File not found" and an %errorlevel%of 1
(All output of dir is redirected to nul to keep the screen clear - change that, if you want that output).
&& works as "if previous command was successful then" ("if %errorlevel% is not 0")

Unable to pause the running batch file for waiting user input intermediately

I couldn't able to pause the running batch file for asking user input intermediately. I tried the commands like PAUSE and SET /P aaa="Press enter to exit" and also as following but nothing worked out.
#ECHO OFF
SET /p aaa="Press enter to exit"
ECHO you typed %aaa%
PAUSE
My batch file internally invokes another batch to build all visual studio projects under the root of the baseline.
One of the project build is getting failed and finally it returns '1' as BUILD FAILED to the main batch file processor. This terminates the MS DOS console immediately and not waiting for user input.
I'm unable to see the MS DOS console window with the end results.
There are various steps to see the end results(Writing the execution output to a text file as like C:\CurrentApp\MyBuild>ABC.bat MyApp.New.BUILD > output.txt) but i would like to see in MS DOS console screen itself with blinking cursor waiting for any user input key.
My batch file looks like:
cd C:\CurrentApp\MyBuild
ABC.bat MyApp.New.BUILD
SET /p aaa="Press enter key to exit"
PAUSE
#ECHO OFF
SET /p aaa="Press enter key to exit"
ECHO you typed %aaa%
PAUSE
You must call your second batch: call ABC.bat MyApp.New.BUILD. Otherwise control passes to ABC.bat but never returns so your pause is never executed. You may think of it as of ABC.bat overwriting your current batch contents and then executing itself.

Resources