Categories
Scripts Windows Batch

Variables

02Variables.bat

::this program will demonstrate variables in batch file
@echo off

::set is used to declare and initialize variables
::by default variables are declared in global scope
set var1=I am global variable

::to print the value of variable surrount by %%
echo "var1 value:: %var1%"

::to declare variable in local scope
SETLOCAL
set var_2=I am the local variable, my life limited to SETLOCAL block
echo %var_2 value:: var_2%
ENDLOCAL
::ENDLOCAL is used to terminate the local block and scope, var_2 variable will be destroyed & dead after this.

echo "var_2 value after ENDLOCAL:: %var_2%"

::/A param used to assign numeric value
set /A data_num=100
echo "data_num value:: %data_num%"


Output

Categories
Scripts Windows Batch

A Batch script

End user can interact with Windows OS in two ways either by Graphical interface or through Command Line commands & scripting. For example one can do Ctrl+c, Ctrl+v to copy paste file. Or we can use Copy command in command line(cmd) to copy file. Batch scripts are always run on Command Line.

How to open command line.

  1. press Windows Key + R to open Run and write cmd to open.
  2. or write “Command Prompt” in windows startup menu search to open that app.
Command Prompt

On command prompt we can enter commands to do tasks we want. For example lets print current date.

Output of Date command.

What is Command – Commands are inbuilt programs provided by Operating system. They can be run on Command prompt. Also command can receive input arguments. Here “date” is command, “/t” is argument which says display current date only.

What is Script – In real life, tasks can be more complex rather than printing only current date. For example we would want to take backup all files from directory called “Customer Records” everyday at 12 midnight and copy them to another folder & turn off machine. Single OS command cannot achieve this task. Script is the answer. It is batch programming language, which can be used together with in-built commands to create .bat file. Then “.bat” files can be run on command line. Batch programs are stored in file with extension .bat.

01HelloWorld.bat

@echo off
echo "Hello World, this is first batch program"
pause

Output

Design a site like this with WordPress.com
Get started