- /* steve jansen */
- // another day in paradise hacking code and more
- Guide to Windows Batch Scripting
- Why Windows?
- Why DOS-style Batch Files?
- Series Parts
- Comments
- Guides
- Recent Posts
- Social Stuff
- Windows batch script programming
- Batch file – Programming tutorial
- Batch File Programming tutorial
- Batch File Programming – Introduction
- How to create a batch file?
- How to run a batch file?
- Explanation of the program
- Batch File Programming – DOs and DON’Ts
- Some final words of advice before you start playing around batch commands
- Batch Script — Quick Guide
- Batch Script — Environment
- Writing and Executing
- Environment Variables
- Batch Script — Commands
- Batch Script — Files
- Creating Batch Files
- Saving Batch Files
- Executing Batch Files
- Modifying Batch Files
- Batch Script — Syntax
- ECHO Command
- Documentation
- First Batch Script Program
- Batch Script — Variables
- Command Line Arguments
- Set Command
- Syntax
- Example
- Output
- Working with Numeric Values
- Local vs Global Variables
- Example
- Output
- Working with Environment Variables
- Batch Script — Comments
- Comments Using the Rem Statement
- Syntax
- Example
- Output
- Comments Using the :: Statement
- Syntax
- Example
- Output
- Batch Script — Strings
- Batch Script — Arrays
- Creating an Array
- Example
- Output
- Accessing Arrays
- Example
- Modifying an Array
- Example
- Iterating Over an Array
- Output
- Length of an Array
- Output
- Creating Structures in Arrays
- Example
- Output
- Batch Script — Decision Making
- Batch Script — Operators
- Arithmetic Operators
- Relational Operators
- Logical Operators
- Assignment Operators
- Bitwise Operators
- Batch Script — DATE and TIME
- Syntax
- Example
- Output
- Syntax
- Example
- Output
- Date in Format Year-Month-Day
- Example
- Output
- Batch Script — Input / Output
- Redirecting Output (Stdout and Stderr)
- Suppressing Program Output
- Stdin
- Batch Script — Return Code
- Error Level
- Syntax
- Example
- Output
- Loops
- Looping through Command Line Arguments
- Example
- Output
- Batch Script — Functions
- Function Definition
- Example
- Batch Script — Process
- Viewing the List of Running Processes
- Syntax
- Examples
- Killing a Particular Process
- Syntax
- Examples
- Starting a New Process
- Syntax
- Examples
- Batch Script — Aliases
- Creating an Alias
- Syntax
- Example
- Output
- Deleting an Alias
- Example
- Replacing an Alias
- Example
- Batch Script — Devices
- Syntax
- Examples
- Batch Script — Registry
- Batch Script — Network
- Batch Script — Printing
- Syntax
- Example
- Command Line Printer Control
- Syntax
- Testing if a Printer Exists
- Example
- Batch Script — Debugging
- Error Messages
- Complex Command Lines
- Subroutines
- Windows Versions
- Batch Script — Logging
- Syntax
- Example
- Output
/* steve jansen */
// another day in paradise hacking code and more
Guide to Windows Batch Scripting
I love shell scripting – it’s the duct tape of programming to me. Low cost, high benefit. And it feels like art, where one can learn to do increasingly complex tasks with greater simplicity.
Sadly, I feel like it’s a developer skill on the decline. Maybe new developers feel it’s “not real programming”. Perhaps the growing dominance of Java as the lingua franca of academic comp sci courses has made shell scripting less relevant in university settings.
True, shell scripting feel a bit “vocational”, maybe even a bit unsexy compared to Python/Ruby/LISP/blah/blah/blah. Nevertheless, it’s a skill that becomes invaluable as you gain seniority and start doing more DevOps in you day job, or if you want to do some high-speed, low drag stuff to tailor your development environment like this.
Why Windows?
This series will share some of the tips and tricks I’ve picked up through the years of working with Windows professionally. I’ll be the first to admit the Unix shells of the world are far superior to the Windows command prompt (or even Windows PowerShell). Windows is a fact of life for most professionals writing code for coporate customers; this series aims to make life with Windows a little easier.
Why DOS-style Batch Files?
This series will share some conventions I picked up along the way for scripting in Windows via command prompt batch files. The Windows PowerShell is definitely sweet, but, I still like batch files for their portability and low friction. The Windows command line is very stable – no worrying about the PowerShell interpreter path, which version of PowerShell the server is running, etc.
Series Parts
Posted by Steve Jansen Mar 1 st , 2013 batch, scripting, shell, windows
Comments
Hi, I’m Steve. I’m a software developer loving life in Charlotte, NC, an (ISC) 2 CSSLP and an avid fan of Crossfit.
And, no, I’m not Steve Jansen the British jazz drummer, though that does sound like a sweet career.
Guides
Recent Posts
Social Stuff
- @steve-jansen on GitHub
- @steve-jansen on StackOverflow
- @steve-jansen ProTips on Coderwall
- @steve-jansen on Microsft Connect
- @steve-jansen on ASP.NET User Voice
- Subscribe via RSS
Copyright © 2015 — Steve Jansen — Powered by Octopress
Windows batch script programming
In Windows, the batch file is a file that stores commands in a serial order. Command line interpreter takes the file as an input and executes in the same order. A batch file is simply a text file saved with the .bat file extension. It can be written using Notepad or any other text editor.
A simple batch file will be
After saving it with .bat extension. Double click it to run the file. It prints shows
In above script, ECHO off cleans up the console by hiding the commands from being printed at the prompt, ECHO prints the text “GeeksforGeeks” to the screen, and then waits for the user to press a key so program can be ceased.
Some basic commands of batch file
- echo – Prints out the input string. It can be ON or OFF, for ECHO to turn the echoing feature on or off. If ECHO is ON, the command prompt will display the command it is executing.
- cls – Clears the command prompt screen.
- title: Changes the title text displayed on top of prompt window.
- EXIT – To exit the Command Prompt.
- pause – Used to stop the execution of Windows batch file.
- :: – Add a comment in the batch file.
- COPY – Copy a file or files
Types of “batch” files in Windows
- INI (*.ini) – Initialization file. These set the default variables for the system and programs.
- CFG (*.cfg) – These are the configuration files.
- SYS (*.sys) – System files, can sometimes be edited, mostly compiled machine code in new versions.
- COM (*.com) – Command files. These are the executable files for all the DOS commands. In early versions there was a separate file for each command. Now, most are inside COMMAND.COM.
- CMD (*.cmd) – These were the batch files used in NT operating systems.
Lets take another example,
Suppose we need to list down all the files/directory names inside a particular directory and save it to a text file, so batch script for it will be,
Now when we run this batch script, it will create a file name geeks_list.txt in your C:\ directory, displaying all the files/folder names in C:\Program Files
Another useful batch script that can be written to diagnose your network and check performance of it.
This script displays,
This script gives information about the current network and some network packet information. ‘ipconfig /all’ helps to view the network information and ‘ping’ & ‘tracert’ to get each packet info. Learn about ping and traceroute here.
Batch file – Programming tutorial
Many of us have heard or perhaps known about the batch file, but very few are aware of its power and dominance in Windows. Almost everything can be done when we know relevant command line instructions. So in this series of tutorials, we will learn about batch file programming and how we can execute command line instructions with a single click through them.
Batch File Programming tutorial
Batch File Programming – Introduction
A batch file is an unformatted text file or script file which contains multiple commands to achieve a certain task. It contains series of command that is executed by command line interpreter.
Extensions: .bat or .cmd
The instructions in batch files are for automating repetitive command sequences.
Before the implementation of modern GUI’s ( Graphical User Interface ), in the operating system like MS-DOS, we had to operate every command from command line. Even though we are facilitated with GUI’s, many major core operations can only be achieved through command line instructions.
So whenever we write instructions or codes in batch files, we are executing command line operations through our instructions and when we know how to write commands, we can do many powerful things in the Windows.
For example: We can create a .bat file with instructions of shutting down and whenever clicked in that file, Windows will automatically shut down.
Sounds fun, right?
How to create a batch file?
Well as simple as it sounds, you don’t need any extra software installed to create a batch file.
Just open up a built-in text editor for windows.
After writing commands, all you need to do is save it as a .bat or .cmd file.
Voila, you have created your first ever batch file. But you haven’t put any instructions. We will cover about programming and scripting in next articles.
Now that you know how to create a batch file, you must be wondering how to run it?
How to run a batch file?
It may sound funny, but all you have to do is click that file to run it and Windows will automatically run the commands written in a batch file.
A batch file can also be run via command prompt. In order to execute the batch file from command prompt, we must set the path to the directory where the batch file is stored or we should include the path address to that directory.
Let’s create a simple batch script to display “This is my first script”.
- First, open up a text editor and save the file as a .bat file
- Copy and paste the code above and click on that file to run the script
It will generate an output like this.
Explanation of the program
Line 1:
If we don’t put @echo off at the top of the script, it will produce an output where ‘echo’ itself will also be displayed. And the output becomes like:
So to avoid the display of command itself, we must use @echo off at the top.
Line 2:
Line 2 just echoes ‘This is my first script’ onto the console.
Line 3: Pause is used to hold the screen until we press a key. If pause is not used, the output screen will vanish away within a blink of an eye and we won’t be able to see the output.
Batch File Programming – DOs and DON’Ts
You must always follow best programming practice while writing codes, be it batch file programming or any.
Even in short programs, we must maintain the habit of following better practice because while we write huge programs, it becomes a nightmare to debug it and also maintain it because no one else will understand your code if not properly documented.
So here are the few things that must be implemented and few things that must be avoided while coding.
DOs
- Documenting code with comments
Perhaps this is one of the most important one because without proper documentation it becomes tedious to maintain the code and debug it .
So it is always a good idea to insert comments in programs or codes, explaining what the next lines or block of code is trying to accomplish, how and why.
Either REM or : : is used for comments in batch file programming. Here is the example.
As simple as it is to code batch files, so is to hack and tweak the code because everything is like plain English in batch programs. Batch files are weakly typed, so it is always a better approach to validate all the inputs in batch file programming.
Always check the new variable before using them or initializing them because they might already have been defined.
Without proper indentation, a program becomes confusing to intercept. So always use proper indentation in every line of code for better understanding of the code.
DON’Ts
If there are few things to be considered for better programming practice, there are also certain things that must be avoided. Here are the few things that you as a programmer should try to avoid while coding.
- Avoid one-liner codes (multiple command lines joined into a single one by ANDs and ORs) and use a block of code.
- Avoid nested block codes (nested if else) and use subroutines instead.
- Don’t use variable names as command names
Some final words of advice before you start playing around batch commands
Now that you have known about the batch files, in the coming tutorials, you will learn about advanced concepts in batch file programming.
But we should warn you that, batch file commands and scripts are too much powerful and if used without proper knowledge, it can crash your machine and software’s functionalities. Make sure you know what you are doing because with batch scripts we are playing with the core feature of Windows.
Batch Script — Quick Guide
Batch Script is incorporated to automate command sequences which are repetitive in nature. Scripting is a way by which one can alleviate this necessity by automating these command sequences in order to make one’s life at the shell easier and more productive. In most organizations, Batch Script is incorporated in some way or the other to automate stuff.
Some of the features of Batch Script are −
Can read inputs from users so that it can be processed further.
Has control structures such as for, if, while, switch for better automating and scripting.
Supports advanced features such as Functions and Arrays.
Supports regular expressions.
Can include other programming codes such as Perl.
Some of the common uses of Batch Script are −
Setting up servers for different purposes.
Automating housekeeping activities such as deleting unwanted files or log files.
Automating the deployment of applications from one environment to another.
Installing programs on various machines at once.
Batch scripts are stored in simple text files containing lines with commands that get executed in sequence, one after the other. These files have the special extension BAT or CMD. Files of this type are recognized and executed through an interface (sometimes called a shell) provided by a system file called the command interpreter. On Windows systems, this interpreter is known as cmd.exe.
Running a batch file is a simple matter of just clicking on it. Batch files can also be run in a command prompt or the Start-Run line. In such case, the full path name must be used unless the file’s path is in the path environment. Following is a simple example of a Batch Script. This Batch Script when run deletes all files in the current directory.
Batch Script — Environment
This chapter explains the environment related to Batch Script.
Writing and Executing
Typically, to create a batch file, notepad is used. This is the simplest tool for creation of batch files. Next is the execution environment for the batch scripts. On Windows systems, this is done via the command prompt or cmd.exe. All batch files are run in this environment.
Following are the different ways to launch cmd.exe −
Method 1 − Go to C:\Windows\System32 and double click on the cmd file.
Method 2 − Via the run command – The following snapshot shows to find the command prompt(cmd.exe) on Windows server 2012.
Once the cmd.exe is launched, you will be presented with the following screen. This will be your environment for executing your batch scripts.
Environment Variables
In order to run batch files from the command prompt, you either need to go to the location to where the batch file is stored or alternatively you can enter the file location in the path environment variable. Thus assuming that the batch file is stored in the location C:\Application\bin , you would need to follow these instructions for the PATH variable inclusion.
OS | Output |
---|---|
Windows | Append the String; C:\Application\bin to the end of the system variable PATH. |
Batch Script — Commands
In this chapter, we will look at some of the frequently used batch commands.
S.No | Commands & Description | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1 | VER This batch command shows the version of MS-DOS you are using. This is a batch command that associates an extension with a file type (FTYPE), displays existing associations, or deletes an association. This batch command helps in making changes to a different directory, or displays the current directory. This batch command clears the screen. This batch command is used for copying files from one location to the other. This batch command deletes files and not directories. This batch command lists the contents of a directory. This batch command help to find the system date. This batch command displays messages, or turns command echoing on or off. This batch command exits the DOS console. This batch command creates a new directory in the current location. This batch command moves files or directories between directories. This batch command displays or sets the path variable. This batch command prompts the user and waits for a line of input to be entered. This batch command can be used to change or reset the cmd.exe prompt. This batch command removes directories, but the directories need to be empty before they can be removed. Renames files and directories This batch command is used for remarks in batch files, preventing the content of the remark from being executed. This batch command starts a program in new window, or opens a document. This batch command sets or displays the time. This batch command prints the content of a file or files to the output. This batch command displays the volume labels. Displays or sets the attributes of the files in the curret directory This batch command checks the disk for any problems. This batch command provides a list of options to the user. This batch command invokes another instance of command prompt. This batch command compares 2 files based on the file size. This batch command converts a volume from FAT16 or FAT32 file system to NTFS file system. This batch command shows all installed device drivers and their properties. This batch command extracts files from compressed .cab cabinet files. This batch command searches for a string in files or input, outputting matching lines. This batch command formats a disk to use Windows-supported file system such as FAT, FAT32 or NTFS, thereby overwriting the previous content of the disk. This batch command shows the list of Windows-supplied commands. This batch command displays Windows IP Configuration. Shows configuration by connection and the name of that connection. This batch command adds, sets or removes a disk label. This batch command displays the contents of a file or files, one screen at a time. Provides various network services, depending on the command used. This batch command sends ICMP/IP «echo» packets over the network to the designated address. This batch command shuts down a computer, or logs off the current user. This batch command takes the input from a source file and sorts its contents alphabetically, from A to Z or Z to A. It prints the output on the console. This batch command assigns a drive letter to a local folder, displays current assignments, or removes an assignment. This batch command shows configuration of a computer and its operating system. This batch command ends one or more tasks. This batch command lists tasks, including task name and process id (PID). This batch command copies files and directories in a more advanced way. This batch command displays a tree of all subdirectories of the current directory to any level of recursion or depth. This batch command lists the actual differences between two files. This batch command shows and configures the properties of disk partitions. This batch command sets the title displayed in the console window. Displays the list of environment variables on the current system. Batch Script — FilesIn this chapter, we will learn how to create, save, execute, and modify batch files. Creating Batch FilesBatch files are normally created in notepad. Hence the simplest way is to open notepad and enter the commands required for the script. For this exercise, open notepad and enter the following statements. Saving Batch FilesAfter your batch file is created, the next step is to save your batch file. Batch files have the extension of either .bat or .cmd. Some general rules to keep in mind when naming batch files − Try to avoid spaces when naming batch files, it sometime creates issues when they are called from other scripts. Don’t name them after common batch files which are available in the system such as ping.cmd.
The above screenshot shows how to save the batch file. When saving your batch file a few points to keep in mind.
Executing Batch FilesFollowing are the steps to execute a batch file − Step 1 − Open the command prompt (cmd.exe). Step 2 − Go to the location where the .bat or .cmd file is stored. Step 3 − Write the name of the file as shown in the following image and press the Enter button to execute the batch file.
Modifying Batch FilesFollowing are the steps for modifying an existing batch file. Step 1 − Open windows explorer. Step 2 − Go to the location where the .bat or .cmd file is stored. Step 3 − Right-click the file and choose the “Edit” option from the context menu. The file will open in Notepad for further editing.
Batch Script — SyntaxNormally, the first line in a batch file often consists of the following command. ECHO CommandBy default, a batch file will display its command as it runs. The purpose of this first command is to turn off this display. The command «echo off» turns off the display for the whole script, except for the «echo off» command itself. The «at» sign «@» in front makes the command apply to itself as well. DocumentationVery often batch files also contains lines that start with the «Rem» command. This is a way to enter comments and documentation. The computer ignores anything on a line following Rem. For batch files with increasing amount of complexity, this is often a good idea to have comments. First Batch Script ProgramLet’s construct our simple first batch script program. Open notepad and enter the following lines of code. Save the file as “List.cmd”. The code does the following − Uses the echo off command to ensure that the commands are not shown when the code is executed. The Rem command is used to add a comment to say what exactly this batch file does. The dir command is used to take the contents of the location C:\Program Files. The ‘>’ command is used to redirect the output to the file C:\lists.txt. Finally, the echo command is used to tell the user that the operation is completed. When the above command is executed, the names of the files in C:\Program Files will be sent to the file C:\Lists.txt and in the command prompt the message “The program has completed” will be displayed. Batch Script — VariablesThere are two types of variables in batch files. One is for parameters which can be passed when the batch file is called and the other is done via the set command. Command Line ArgumentsBatch scripts support the concept of command line arguments wherein arguments can be passed to the batch file when invoked. The arguments can be called from the batch files through the variables %1, %2, %3, and so on. The following example shows a batch file which accepts 3 command line arguments and echo’s them to the command line screen. If the above batch script is stored in a file called test.bat and we were to run the batch as Following is a screenshot of how this would look in the command prompt when the batch file is executed. The above command produces the following output. If we were to run the batch as The output would still remain the same as above. However, the fourth parameter would be ignored. Set CommandThe other way in which variables can be initialized is via the ‘set’ command. Following is the syntax of the set command. Syntaxvariable-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. The following example shows a simple way the set command can be used. ExampleIn the above code snippet, a variable called message is defined and set with the value of «Hello World». To display the value of the variable, note that the variable needs to be enclosed in the % sign. OutputThe above command produces the following output. Working with Numeric ValuesIn batch script, it is also possible to define a variable to hold a numeric value. This can be done by using the /A switch. The following code shows a simple way in which numeric values can be set with the /A switch. We are first setting the value of 2 variables, a and b to 5 and 10 respectively. We are adding those values and storing in the variable c. Finally, we are displaying the value of the variable c. The output of the above program would be 15. All of the arithmetic operators work in batch files. The following example shows arithmetic operators can be used in batch files. The above command produces the following output. Local vs Global VariablesIn any programming language, there is an option to mark variables as having some sort of scope, i.e. the section of code on which they can be accessed. Normally, variable having a global scope can be accessed anywhere from a program whereas local scoped variables have a defined boundary in which they can be accessed. DOS scripting also has a definition for locally and globally scoped variables. By default, variables are global to your entire command prompt session. Call the SETLOCAL command to make variables local to the scope of your script. After calling SETLOCAL, any variable assignments revert upon calling ENDLOCAL, calling EXIT, or when execution reaches the end of file (EOF) in your script. The following example shows the difference when local and global variables are set in the script. ExampleFew key things to note about the above program. The ‘globalvar’ is defined with a global scope and is available throughout the entire script. The ‘var‘ variable is defined in a local scope because it is enclosed between a ‘SETLOCAL’ and ‘ENDLOCAL’ block. Hence, this variable will be destroyed as soon the ‘ENDLOCAL’ statement is executed. OutputThe above command produces the following output. You will notice that the command echo %var% will not yield anything because after the ENDLOCAL statement, the ‘var’ variable will no longer exist. Working with Environment VariablesIf you have variables that would be used across batch files, then it is always preferable to use environment variables. Once the environment variable is defined, it can be accessed via the % sign. The following example shows how to see the JAVA_HOME defined on a system. The JAVA_HOME variable is a key component that is normally used by a wide variety of applications. The output would show the JAVA_HOME directory which would depend from system to system. Following is an example of an output. Batch Script — CommentsIt’s always a good practice to add comments or documentation for the scripts which are created. This is required for maintenance of the scripts to understand what the script actually does. For example, consider the following piece of code which has no form of comments. If any average person who has not developed the following script tries to understand the script, it would take a lot of time for that person to understand what the script actually does. Comments Using the Rem StatementThere are two ways to create comments in Batch Script; one is via the Rem command. Any text which follows the Rem statement will be treated as comments and will not be executed. Following is the general syntax of this statement. Syntaxwhere ‘Remarks’ is the comments which needs to be added. The following example shows a simple way the Rem command can be used. ExampleOutputThe above command produces the following output. You will notice that the line with the Rem statement will not be executed. Comments Using the :: StatementThe other way to create comments in Batch Script is via the :: command. Any text which follows the :: statement will be treated as comments and will not be executed. Following is the general syntax of this statement. Syntaxwhere ‘Remarks’ is the comment which needs to be added. The following example shows a simple way the Rem command can be used. ExampleOutputThe above command produces the following output. You will notice that the line with the :: statement will not be executed. Note − If you have too many lines of Rem, it could slow down the code, because in the end each line of code in the batch file still needs to be executed. Let’s look at the example of the large script we saw at the beginning of this topic and see how it looks when documentation is added to it. You can now see that the code has become more understandable to users who have not developed the code and hence is more maintainable. Batch Script — StringsIn DOS, a string is an ordered collection of characters, such as «Hello, World!».
|