Windows BAT script tips


Windows BAT script tips:
A few tips for when writing Windows BAT scripts:

tip: turn OFF echo all lines of script
@ECHO OFF

tip: turn ON local env variables
SETLOCAL

tip: exit a BAT with an error code
REM exit BAT with error code '3' but not the CMD window!
EXIT /b 3

tip: output the name of this script
REM echo out the name of this script (%0)
ECHO [%~n0] doing something now …

tip: check if an environment variable is NOT defined
IF NOT DEFINED _MY_VAR (
  ECHO _MY_VAR is not defined!
  EXIT /b 1

)

tip: create a directory if it does not already exist
IF NOT EXIST "%_MY_DIR%" (MKDIR "%_MY_DIR%")

tip: run a script for each directory:
for /F %%i in ('where /R . fileToFind.txt') do (
    call myScript.bat "%%i" %_someVariable%
    if %ERRORLEVEL% NEQ 0 goto:_EXIT
)

GOTO _EXIT
:_EXIT_ERROR
EXIT /b 3

:_EXIT
EXIT /b 0

tip: type a file to clipboard:
type myFile.txt | clip

tip: check for missing arguments to the BAT script:

if "%~1"=="" (
        echo "USAGE TEXT HERE"
) else (
        REM do something ...
)

Comments