It can be interesting to automate certain repetitive tasks, such as the creation of user accounts. To do this, you can use scripts.
The script will execute according to the defined algorithm a sequence of actions.
start <script_name>.bat
@echo off
at the beginning of the scripttitle <program_title>
mode con cols=80 lines=16
# Here we have 80 columns and 16 rows
color <couleur>
Here is the list of available colors:
Code | Color |
---|---|
0 | Black |
1 | Dark blue |
2 | Green |
3 | Blue-Gray |
4 | Brown |
5 | Purple |
6 | Khaki |
7 | Light Grey |
8 | Grey |
9 | Light Blue |
A | Light Green |
B | Cyan |
C | Red |
D | Rose |
E | Yellow |
F | White |
Note that color coding is done using the hexadecimal base.
cls
exit
echo < text>
::
AND/OR REM
Non-exhaustive list of environment variables :
set <nomVariable>=<valeur>
Warning: variables must begin with an alphabetical character and must not contain any special characters.
set a=2
set b=5
set /a resultat=%a%+%b%
:: result is now 7
The character /a is a switch that allows you to perform calculations. If we hadn't put it, then the result would have been different.
Example :set a=2 set b=5 set result=%a%+%b% :: result is now 2+5
set /p <variable>=Enter your text:
set variable1=Test1
set variable2=%variable1:~1,3%
echo %variable2%
:: returns "est"
if [COMPARE 1] [COMPARANT] [COMPARE 2] (
:: action if the condition is met
) else (
:: action if the condition is not met
)
List of comparators :
Comparison : | Meaning : |
---|---|
equ (or ==) | equal to |
neq | different from... |
lss | less than |
leq | less than or equal to |
gtr | greater than |
geq | greater than or equal to |
Example :
if %variable1% == 12 (
echo variable1 is equal to 12
) else (
echo variable1 is not equal to 12
)
if 42 == 42 echo The world works!
Batch do not provide the possibility to test several conditions at the same time (IF ... AND ... THEN ...). So you need to use several IFs to do this: if value1 lss value2 if value3 lss value4 echo
.
Convert the time to minutes and compare the number of minutes.
Label declaration: :label_name
.
Syntax: goto tag_name
.
Syntax:
for %%variable in (condition) do (
:: instruction
)
Examples :
for %%v in (5 4 3 2 1) do (
echo %%v
)
This will display:
5
4
3
2
1
This syntax can become awkward for large loops.
Note : In loops, variables are called with
%%
and not%
or%variable%
.
There is another syntax, similar to other languages :
for /l %%v in (i_start_value, step, max_value) do (
:: instruction
)
for /d %variable IN (directory)
to execute commands on all files in a directory.for /f ["options"] %variable IN (file.txt)
allows you to browse the text of a file or string.for /r
to process a directory and all its subdirectories.