Getting Started with Batch Script

As previously explained, a simple text editor, such as Notepad, can be used to write Batch Script, although slightly more advanced editors, such as NotePad++, offer the advantage of syntax highlighting, which can make the process easier.

Batch script, contained in either '.bat' or '.cmd' files, known as batch files, run in a command or console window.

Below is a simple example of a Batch Script, which displays the message, 'Hello World', to the screen.

:: Stop output to the screen unless 'echo' is used.
@echo off

:: Display 'Hello World' message.
echo Hello World

:: Keep command window open until a key is pressed.
pause

In the example above, the lines that begin with two colons are comments, allowing for explanatory text to be provided. It should be noted that comments can also be added by preceding a line with 'rem', instead of '::'. This is not case sensitive, so both 'rem' and 'REM' work. The words in blue are known as reserved words, which can only be used for a specific purpose.

The line '@echo off' disables the display prompt so that only lines that start with the word 'echo' are displayed. The 'echo' command then displays the words 'Hello World' in the console. Finally, the 'pause' command, pauses the screen until a key is pressed.

Running a batch script can be done in a few different ways. The simplest of these is just to double click the batch file in Windows Explorer. Doing this opens a command window, where the script runs. Here, the 'pause' command will keep the window open until a key is pressed. Without this, the window may close before the message can be read.

The second method of running a batch file is by typing the full path into a command window and pressing return.

C:\Demo\demo.bat

It should be noted, that if the folder or file name contain a space, then the path should be enclosed in double quotes.

Another way these files can be run is via a Windows Scheduled Task, which can automate the script to run on a specific schedule, for example, every hour, or every day at a specific time.