Windows Batch

Windows batch scripting

· Programming language · Computer programming · Microsoft Windows · Windows batch sink ·


Arg %1 Arg %z Content
%1 ~nz filename without the extension
%~x1 ~nxz filename with extension
%~dp1 `x in (%*) do (
set /A argCount+=1
REM argument x file name
set "argVec[!argCount!]=%%~x"
REM argument x name without file extension
set "argVn[!argCount!]=%%~nx"

## Variables

### %A vs %a vs \A** when used in batch files
Variables are case sensitive

### Init
set /A myVar = 1

Assing the numerical value to myVar
/A is the switch used if the value needs to be numeric


@echo off 
set message=Hello World 
echo %message%

To display the value of the variable, note that the variable needs to be enclosed in the % sign

SET /A a = 5 
SET /A b = 10 
SET /A c = %a% + %b% 
echo %c%

The scope

Global vs local

By default, variables are global to your entire command prompt session. Call the SETLOCAL command to make variables local to the scope of your script. After calling SETLOCAL, any variable assignments revert upon calling ENDLOCAL, calling EXIT, or when execution reaches the end of file (EOF) in your script.

Environment variables

If you have variables that would be used across batch files, then it is always preferable to use environment variables. Once the environment variable is defined, it can be accessed via the % sign.



Creating an array

set a[0]=1

From a list

@echo off 
set list=1 2 3 4 
(for %%a in (%list%) do ( 
   echo %%a 


@echo off 
setlocal enabledelayedexpansion 
set topic[0]=comments 
set topic[1]=variables 
set topic[2]=Arrays 
set topic[3]=Decision making 
set topic[4]=Time and date 
set topic[5]=Operators 

for /l %%n in (0,1,5) do ( 
   echo !topic[%%n]! 


The length of an array is done by iterating over the list of values in the array since there is no direct function to determine the number of elements in an array.


@echo off 
set obj[0].Name=Joe 
set obj[0].ID=1 
set obj[1].Name=Mark 
set obj[1].ID=2 
set obj[2].Name=Mohan 
set obj[2].ID=3 
FOR /L %%i IN (0 1 2) DO  (
   call echo Name = %%obj[%%i].Name%%
   call echo Value = %%obj[%%i].IDa in ('echo/^|date') do ( 
   for /f "tokens = %t%-4 delims=.-/ " %%d in ('date/t') do ( 
      set %%a=%%d&set %%b=%%e&set %%c=G IN ('""%ffpath%exiftool.exe" -b "!argVec[%%i]!" -ImageWidth"') DO SET /A pWidth=%%G

ECHO Image dimensions: !pHeight! by !pWidth!

Tokens and Delims

The general syntax of FOR /F commands is:

FOR /F "tokens=n,m* delims=ccc" %%A IN ('some_command') DO other_command %%A %%B %%C

Tokens are the numbers of the items in the list, that divided into tokens by the delimiter


FOR /F "tokens=2,3 delims= " %%A IN ('PING -a %1') DO IF "%%B"=="[%1]" SET PC=a in ("%STRING%") do (

set var1=Abc_123
rem select from after the underscore to the end
set var2=%var1:*_=%
echo %var2%

ECHO into the same line

echo|set /p ="Executing backup...."
echo|set /p =" backup procedure"

ESC sequences

Colors and styles