Batch File Programming
ERRORLEVEL in parenthesized IF statement
How to avoid
Terminate batch job (Y/N)? prompt
Using drag and drop to process files with a batch file
Terminate batch job (Y/N)?prompt
Exiting most console programs in a batch file with Ctrl-C or Ctrl-Break will usually result in the command interpreter displaying:
Terminate batch job (Y/N)?
Here are a few ways to handle this automatically if your batch file does not run any console programs that read keyboard input from the standard input.
Do this to skip answering the prompt and continue:
Do this to answer the prompt with Y and exit::
ECHO Y | MyBat.bat
Do this to answer the prompt with N and continue::
ECHO N | MyBat.bat
Consider the following batch file compound IF statement.
@ECHO OFF SetErr 0 SET A=15 IF "%A%"=="16" ( SetErr 1 SET ERR=%ERRORLEVEL% ) ELSE ( SetErr 1 SET ERR1=%ERRORLEVEL% SetErr 2 SET ERR2=%ERRORLEVEL% SetErr 3 SET ERR3=%ERRORLEVEL% ) SET ERRX=%ERRORLEVEL% ECHO ERR1=%ERR1% ECHO ERR2=%ERR2% ECHO ERR3=%ERR3% ECHO ERRX=%ERRX% PAUSE
The output is:
ERR1=0 ERR2=0 ERR3=0 ERRX=3 Press any key to continue . . .
Note that SetErr is a console program that returns ERRORLEVEL given on the command line. The output expected is:
ERR1=1 ERR2=2 ERR3=3 ERRX=3
It appears that ERRORLEVEL is not updated until the last statement contained within the parens is executed. So, if you need to evaluate ERRORLEVEL between statements, DO NOT include those statements within a parenthesized IF. Instead, do something like this:
SetErr 0 SET A=16 IF "%A%"=="15" (GOTO A15) ELSE GOTO A16 :A15 SetErr 1 SET ERR=%ERRORLEVEL% GOTO SHOWERRS :A16 SetErr 1 SET ERR1=%ERRORLEVEL% SetErr 2 SET ERR2=%ERRORLEVEL% SetErr 3 SET ERR3=%ERRORLEVEL% GOTO SHOWERRS :SHOWERRS ECHO ERR1=%ERR1% ECHO ERR2=%ERR2% ECHO ERR3=%ERR3% PAUSE
ERR1=1 ERR2=2 ERR3=3
When you drag a file in Windows Explorer and drop it on a batch
file, or a shortcut to a batch file, the working directory is path of
the dropped file. Also,
%0 will contain the fully
qualified path and file of the batch file. If the file name needs to
be double-quoted to be passed to the BAT file as a parameter, it is
automatically double-quoted. You can remove the double quotes with
%~1. So, for example, if you want to suffix
the file name before using it, do this:
Note that if the batch is run from a command prompt,
%0 will contain
the name of the batch file as it was typed at the command prompt.
Here is a small batch you can use to test this behavior yourself:
@ECHO OFF ECHO %%0=%0 ECHO %%1=%1 ECHO Working directory is: %CD% ECHO Fully qualified BAT file=%~f0 ECHO Fully qualified dropped file=%~f1 ECHO To change to BAT file path: CD /D "%~d0%~p0" ECHO Dropped file with suffix: "%~1.txt" PAUSE
If this default behavior is not what you want, you can change the directory to
the BAT file path with
CD /D "%~d1%~p1".