Table of Contents

About

The batch script is a text file with the extension .bat or .cmd that is interpreted by a batch interpreter.

How to

Call a script from a script

You can call a batch script by :

  • writing its name in the source script: The script execution will stop and continue in the called batch
  • using the following commands:
    • call: Calls one batch program from another. The script execution will continue after the called batch is completed
    • start: Starts a separate window to run a specified program or command.

If the script is called from Explorer with a double-click on the batch file, an exit will automatically be performed at the end of the execution.

Determine the directory of the script

See argument modifiers for more options.

  • for a file (not a symlink)
SET SCRIPT_PATH=%~dp0

REM I see also after
FOR %%i IN ("%SCRIPT_PATH%") DO SET SCRIPT_PATH=%%~fsi

REM or
call "%~dp0script.cmd"
  • for a symlink, we need the target directory.
:: The directory of the called file (the symlink)
SET SCRIPT_DIR=%~dp0

:: If this is a symlink, the DIR command gives us the symlink target directory between [ ]
SET SCRIPT_PATH=%~dpnx0
for /F "usebackq tokens=2 delims=[]" %%H in  (`dir /a:l %SCRIPT_PATH%`) do (
	set SCRIPT_DIR=%%~dpH
)
echo %SCRIPT_DIR%

Name

Thanks to argument modifiers - the file name (ie script.bat)

SET SCRIPT_NAME=%~nx0 

Path

%~dpnx0

Control a argument

argument

set allowedvalues=1 2 3
for %%i in ( %allowedvalues% ) do (
    if %1 == %%i set allowed=true
)

Example

Show a banner

set BASE_PATH=%~dp0
type "%BASE_PATH%banner.txt"

where:

Activate Advance Modes

VERIFY whatever 2>nul
SETLOCAL enableExtensions enableDelayedExpansion
IF ERRORLEVEL 1 echo Cannot enable delayed expansion&& exit /b 1

where:

Java

if defined JAVA_HOME if exist "%JAVA_HOME%\bin\java.exe" PATH "%JAVA_HOME%\bin";%PATH%
java.exe -version >nul 2>&1 || ( echo Java cannot be found on the system! & exit /b 2 )
for /f  tokens^=2^,3^,4^ delims^=_.^"  %%J in ('java.exe -version 2^>^&1') do set "jver=%%J%%K%%L" && goto :break_loop
:break_loop
IF %jver%0 LSS 1600 ( echo Current Java version is older than 1.6.0 & endlocal & exit /b 2 )

where: