Don’t be careless with these commands! Practising deleting files directly in your C-drive might have disastrous consequences!

This tutorial is your introduction to writing a batch file. We discussed using the Windows CLI in the Windows Command Line Basics tutorial. There may come a time when you want to run a set of commands repeatedly, possibly even on a scheduled basis. This is where writing a batch file comes into the picture.

Just a file

A batch file is a simple text file with a .bat extension. You can create and edit a batch file with a normal text editor, or using the text and file commands within the CLI itself.

The batch file contains as many commands as needed to fulfill a specific task. The commands are entered sequentially in the batch file, creating a script.

The batch file itself can be run from the CLI.

Hello World!

Set up

  1. Open File Explorer and navigate to your Documents folder
  2. Create a new folder named BatchTest and open it
  3. Open the cmd prompt
  4. Arrange your File Explorer and cmd prompt windows side-by-side

Manual

Type echo Hello World! at the command prompt and press Enter.

Batch file

  1. Create a file named hw.bat in your BatchTest folder
  2. Open it with any text editor
  3. Enter the text echo Hello World! and then save and close hw.bat
cls
echo Hello World!

Test

  1. Type hw at the command prompt and press Enter
  2. The text Hello World! will be output at the command prompt
A screenshot of the batch file being run in the "Hello World!" batch file tutorial.
A screenshot of the batch file being run in the “Hello World!” batch file tutorial.

Next steps

Make your scripts more versatile using Environment variables — watch out for the tutorial More Windows batch files


References:

  1. Wate, Y. (2023) 4 Different Ways to Create a File Using Command Prompt on WindowsTechPP. Available at: https://techpp.com/2021/08/22/create-file-using-command-prompt-guide/ (Accessed: 29 April 2024).

By MisterFoxOnline

Mister Fox AKA @MisterFoxOnline is an ICT, IT and CAT Teacher who has just finished training as a Young Engineers instructor. He has a passion for technology and loves to find solutions to problems using the skills he has learned in the course of his IT career.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.