#variables #arithmetic #environmentalvariables #arrays #conditionals #errorlevel #commandsubstitution #interfacing #datetime #date #time
This snippet contains:
Dos.Batch.Variables.bat : Simple variable declaration and use Dos.Batch.Strings.bat : Strings and String Methods Dos.Batch.Environmental.bat : Examples of Environmental Variables Dos.Batch.Arrays : Examples of Arrays use Dos.Batch.Conditionals : Examples of Conditional use (If Else) Dos.Batch.Loops : Examples of Loops (For etc) Dos.Batch.ErrorLevel : Handling the error level of commands Dos.Batch.CommandSub : Command Substitution, storing the output of a command in a var Dos.Batch.Interfacing : Interfacing dos with other languages, like python and perl. Call perl / py scripts from batch scripts. Dos.Batch.DateTime : DateTime Manipulation
:: Command Line Arguments
@echo off
echo %1
echo %2
echo %3
:: Set Command
set /A variable-name=value
:: where,
::variable-name is the name of the variable you want to set.
::value is the value which needs to be set against the variable.
::/A – This switch is used if the value needs to be numeric in nature.
:: Ex 1
@echo off
set message=Hello World
echo %message%
:: Working with Numbers
@echo off
SET /A a=5
SET /A b=10
SET /A c=%a% + %b%
echo %c%
@echo off
SET /A a=5
SET /A b=10
SET /A c=%a% + %b%
echo %c%
SET /A c=%a% - %b%
echo %c%
SET /A c=%b% / %a%
echo %c%
SET /A c=%b% * %a%
echo %c%
:: Local vs Global vars
@echo off
set globalvar=5
SETLOCAL
set var=13145
set /A var=%var% + 5
echo %var%
echo %globalvar%
ENDLOCAL
:: Environment Variables
@echo off
echo %JAVA_HOME%
A. CREATE STRING
@echo off
:: This program just displays Hello World
set message = Hello World
echo %message%
B. Empty String
B.1 Check for existence of empty string
SET A=
@echo off
SET a =
SET b = Hello
if [%a%] == [] echo "String A is empty"
if [%b%] == [] echo "String B is empty "
C. Interpolation
@echo off
SET a = Hello
SET b = World
SET /A d = 50
SET c = %a% and %b% %d%
echo %c%
Hello and World 50
D. Concatenation
@echo off
SET a = Hello
SET b = World
SET c = %a% and %b%
echo %c%
E. Length of String (Custom)
@echo off
set str = Hello World
call :strLen str strlen
echo String is %strlen% characters long
exit /b
:strLen
setlocal enabledelayedexpansion
:strLen_Loop
if not "!%1:~%len%!"=="" set /A len+ = 1 & goto :strLen_Loop
(endlocal & set %2 = %len%)
goto :eof
F. INTEGERS + ROUNDUP
@echo off
set var = 13145
set /A var = %var% + 5
echo %var%
%variable:~num_chars_to_skip%
%variable:~num_chars_to_skip,num_chars_to_keep%
%variable:~num_chars_to_skip, -num_chars_to_keep%
%variable:~-num_chars_to_skip,num_chars_to_keep%
%variable:~-num_chars_to_skip,-num_chars_to_keep%
G. ALIGN TEXT TO RIGHT
@echo off
set x = 1000
set y = 1
set y = %y%
echo %x%
set y = %y:~-4%
echo %y%
H. SUBSTRING (LEFT STRING)
@echo off
set str = Helloworld
echo %str%
set str = %str:~0,5%
echo %str%
J. SUBSTRING (MID STRING)
@echo off
set str = Helloworld
echo %str%
set str = %str:~5,10%
echo %str%
KS SUBSTRING (RIGHT STRING)
@echo off
set str = This message needs changed.
echo %str%
set str = %str:~-8%
echo %str%
K. REMOVE SUBSTRING
@echo off
set str = Batch scripts is easy. It is really easy.
echo %str%
set str = %str:is =%
echo %str%
L. REMOVE BOTH ENDS OF SUBSTRING
@echo off
set str = Batch scripts is easy. It is really easy
echo %str%
set str = %str:~1,-1%
echo %str%
M. REMOVE ALL SPACES
@echo off
set str = This string has a lot of spaces
echo %str%
set str = %str: =%
echo %str%
O. REPLACE IN STRING
@echo off
set str = This message needs changed.
echo %str%
set str = %str:needs = has%
echo %str%
$ set /?
::Syntax
::Syntax of the set command is very simple. [variable] and [string] parts are optional and used according to situation
::SET [variable=[string]]
::SET [variable=[string]]
:: List All Environment Variables
:: Environment variables holds a lot of information about the operating system
:: and user . All these information can be listed just issuing the set command
:: without any parameter like below.
$ set
:: Get/Print Single Environment Variable
:: In previous example we have listed all environment variables without selecting
:: particular one. We can print only single variable just proving the variable name to the set command. In this example we will print the values of APPDATA environment variable.
$ set APPDATA
:: Get/Print Single Environment Variable
:: Change/Create Environment Variable
:: Now the last function of the set command. We can create or change and
:: environment variable and its value by giving both the variable name and
:: the variable data. In this example we create a new variable named Test
:: with value 1
$ set Test=1
:: Get Home Path
:: Home is the current users location where his personal files and folders stored.
:: This path can be printed like below.
:: LEARN MORE Javascript Array Variable Types
$ set HOMEPATH
:: Get Logon Server
:: Logon server is used to authenticate the user to login a system. In active
:: directory system user credentials are authenticated in these authority servers.
$ set LOGONSERVER
:: Get Path Variable
:: Path variable is used to find executable files. Path variable stored more
:: than one path and if a command is issued these path are checked for this
:: command executables to run.
$ set PATH
:: Get Program Files Path
:: Windows operating system stores built-in and 3 party applications files and
:: folder in Program Files directory. This directory path can be printed like below.
$ set ProgramFiles
:: Get System Root
:: Windows operating system files, folders and libraries are stored in System Root
:: and this root directory generally named windows . By default this path is C:\Windows .
:: The system root can be printed like below.
$ set SystemRoot
:: Get Username
:: The currently logged users user name can be printed like below.
$ set USERNAME
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: Creating an array
set a[0] = 1
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: Optional way to create array - Iterate through list of values
@echo off
set list = 1 2 3 4
(for %%a in (%list%) do (
echo %%a
))
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: ACCESSING ARRAY ELEMENTS
@echo off
set a[0] = 1
set a[1] = 2
set a[2] = 3
echo The first element of the array is %a[0]%
echo The second element of the array is %a[1]%
echo The third element of the array is %a[2]%
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: MODIFYING ARRAY
@echo off
set a[0] = 1
set a[1] = 2
set a[2] = 3
Rem Adding an element at the end of an array
Set a[3] = 4
echo The last element of the array is %a[3]%
::You can modify an existing element of an Array by
::assigning a new value at a given index as shown in the following example −
@echo off
set a[0] = 1
set a[1] = 2
set a[2] = 3
Rem Setting the new value for the second element of the array
Set a[1] = 5
echo The new value of the second element of the array is %a[1]%
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: ITERATING OVER ARRAY
:: CASE 1 - WE KNOW SIZE
Iterating Over an Array
Iterating over an array is achieved by using the ‘for’ loop and going through each element of the array. The following example shows a simple way that an array can be implemented.
@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]!
)
:: CASE 2 - WE DONT
set sources[0]=C:\Users\P.Doulgeridis\Desktop\SAPRUN00FILE\AAyymmddm1.txt
set sources[1]=C:\Users\P.Doulgeridis\Desktop\SAPRUN00FILE\AAyymmddm1EPAN.txt
set sources[2]=C:\Users\P.Doulgeridis\Desktop\SAPRUN00FILE\AAyymmddm1PPC.txt
set sources[3]=C:\Users\P.Doulgeridis\Desktop\SAPRUN00FILE\ALyymmddm1.V51.txt
set sources[4]=C:\Users\P.Doulgeridis\Desktop\SAPRUN00FILE\ALyymmddm1.V52.txt
for /F "tokens=2 delims==" %%s in ('set sources[') do (
IF NOT EXIST %%s (
CALL:error10 "225" "UNABLE TO LOCATE TARGET FILE %%s "
CALL:ERRORNOTIFYMAIL "UNABLE TO LOCATE TARGET FILE %%s" "FATAL" "CHECK EXISTENCE OF TARGET FILES"
EXIT /B 11
) ELSE (
ECHO TARGET DIRECTORY %%s LOCATED SUCCESFULLY
ECHO.
)
set /a "numberoffilesout+=1"
)
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: LENGTH OF ARRAY
::Length of an Array
::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 Arr[0] = 1
set Arr[1] = 2
set Arr[2] = 3
set Arr[3] = 4
set "x = 0"
:SymLoop
if defined Arr[%x%] (
call echo %%Arr[%x%]%%
set /a "x+=1"
GOTO :SymLoop
)
echo "The length of the array is" %x%
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: CREATING STRUCTURES IN ARRAYS
:: Creating Structures in Arrays
:: Structures can also be implemented in batch files using a little
:: bit of an extra coding for implementation. The following example
:: shows how this can be achieved.
Example
@echo off
set len = 3
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
set i = 0
:loop
if %i% equ %len% goto :eof
set cur.Name =
set cur.ID =
for /f "usebackq delims ==. tokens = 1-3" %%j in (`set obj[%i%]`) do (
set cur.%%k = %%l
)
echo Name = %cur.Name%
echo Value = %cur.ID%
set /a i = %i%+1
goto loop
::The following key things need to be noted about the above code.
::Each variable defined using the set command has 2 values associated
::with each index of the array.
::The variable i is set to 0 so that we can loop through
::the structure will the length of the array which is 3.
::We always check for the condition on whether the value
::of i is equal to the value of len and if not, we loop through the code.
::We are able to access each element of the structure using the obj[%i%] notation.
:: Checking integers
@echo off
SET /A a=5
SET /A b=10
SET /A c=%a% + %b%
if %c%==15 echo "The value of variable c is 15"
if %c%==10 echo "The value of variable c is 10"
:: Checking strings
@echo off
SET str1=String1
SET str2=String2
if %str1%==String1 echo "The value of variable String1"
if %str2%==String3 echo "The value of variable c is String3"
:: Checking command line arguments
@echo off
echo %1
echo %2
echo %3
if %1%==1 echo "The value is 1"
if %2%==2 echo "The value is 2"
if %3%==3 echo "The value is 3"
:: One lien if else
@echo off
SET /A a=5
SET /A b=10
SET /A c=%a% + %b%
if %c%==15 (echo "The value of variable c is 15") else (echo "Unknown value")
if %c%==10 (echo "The value of variable c is 10") else (echo "Unknown value")
:: One lien if else strings
@echo off
SET str1=String1
SET str2=String2
if %str1%==String1 (echo "The value of variable String1") else (echo "Unknown value")
if %str2%==String3 (echo "The value of variable c is String3") else (echo "Unknown value")
:: One line - parameter test
@echo off
echo %1
echo %2
echo %3
if %1%==1 (echo "The value is 1") else (echo "Unknown value")
if %2%==2 (echo "The value is 2") else (echo "Unknown value")
if %3%==3 (echo "The value is 3") else (echo "Unknown value")
:: If defined
@echo off
SET str1=String1
SET str2=String2
if defined str1 echo "Variable str1 is defined"
if defined str3 (echo "Variable str3 is defined") else (echo "Variable str3 is not defined")
:: If exist
@echo off
if exist C:\set2.txt echo "File exists"
if exist C:\set3.txt (echo "File exists") else (echo "File does not exist")
:: If errorlevel - multiline block
@echo off
if ERRORLEVEL == 0 (
echo GP Manager is up
goto Continue7
)
echo GP Manager is down
:Continue7
:: if %ERRORLEVEL% - MULTILINE
@echo off
if %ERRORLEVEL% == 0 (
msg * 1st line WORKS FINE rem You can relpace msg * with any othe operation...
goto Continue1
)
:Continue1
If exist "C:\Python31" (
msg * 2nd line WORKS FINE rem You can relpace msg * with any othe operation...
goto Continue2
)
:Continue2
If exist "C:\Python31\Lib\site-packages\PyQt4" (
msg * 3th line WORKS FINE rem You can relpace msg * with any othe operation...
goto Continue3
)
:Continue3
msg * 4th line WORKS FINE rem You can relpace msg * with any othe operation...
goto Continue4
)
:Continue4
msg * "Tutto a posto" rem You can relpace msg * with any othe operation...
pause
:: Nested if
@echo off
SET /A a=5
SET /A b=10
if %a%==5 if %b%==10 echo "The value of the variables are correct"
:: if errorlevel
if errorlevel n somecommand
:: if + go to
@echo off
SET /A a=5
if %a%==5 goto :labela
if %a%==10 goto :labelb
:labela
echo "The value of a is 5"
exit /b 0
:labelb
echo "The value of a is 10"
FOR /F "tokens=* USEBACKQ" %%F IN (`command`) DO (
SET var=%%F
)
ECHO %var%
I always use the USEBACKQ so that if you have a string to insert or a long file name, you can use your double quotes without screwing up the command.
Now if your output will contain multiple lines, you can do this
SETLOCAL ENABLEDELAYEDEXPANSION
SET count=1
FOR /F "tokens=* USEBACKQ" %%F IN (`command`) DO (
SET var!count!=%%F
SET /a count=!count!+1
)
ECHO %var1%
ECHO %var2%
ECHO %var3%
ENDLOCAL
rem https://stackoverflow.com/questions/6359820/how-to-set-commands-output-as-a-variable-in-a-batch-file