Windows batch script programming

Содержание
  1. /* steve jansen */
  2. // another day in paradise hacking code and more
  3. Guide to Windows Batch Scripting
  4. Why Windows?
  5. Why DOS-style Batch Files?
  6. Series Parts
  7. Comments
  8. Guides
  9. Recent Posts
  10. Social Stuff
  11. Windows batch script programming
  12. Batch file – Programming tutorial
  13. Batch File Programming tutorial
  14. Batch File Programming – Introduction
  15. How to create a batch file?
  16. How to run a batch file?
  17. Explanation of the program
  18. Batch File Programming – DOs and DON’Ts
  19. Some final words of advice before you start playing around batch commands
  20. Batch Script — Quick Guide
  21. Batch Script — Environment
  22. Writing and Executing
  23. Environment Variables
  24. Batch Script — Commands
  25. Batch Script — Files
  26. Creating Batch Files
  27. Saving Batch Files
  28. Executing Batch Files
  29. Modifying Batch Files
  30. Batch Script — Syntax
  31. ECHO Command
  32. Documentation
  33. First Batch Script Program
  34. Batch Script — Variables
  35. Command Line Arguments
  36. Set Command
  37. Syntax
  38. Example
  39. Output
  40. Working with Numeric Values
  41. Local vs Global Variables
  42. Example
  43. Output
  44. Working with Environment Variables
  45. Batch Script — Comments
  46. Comments Using the Rem Statement
  47. Syntax
  48. Example
  49. Output
  50. Comments Using the :: Statement
  51. Syntax
  52. Example
  53. Output
  54. Batch Script — Strings
  55. Batch Script — Arrays
  56. Creating an Array
  57. Example
  58. Output
  59. Accessing Arrays
  60. Example
  61. Modifying an Array
  62. Example
  63. Iterating Over an Array
  64. Output
  65. Length of an Array
  66. Output
  67. Creating Structures in Arrays
  68. Example
  69. Output
  70. Batch Script — Decision Making
  71. Batch Script — Operators
  72. Arithmetic Operators
  73. Relational Operators
  74. Logical Operators
  75. Assignment Operators
  76. Bitwise Operators
  77. Batch Script — DATE and TIME
  78. Syntax
  79. Example
  80. Output
  81. Syntax
  82. Example
  83. Output
  84. Date in Format Year-Month-Day
  85. Example
  86. Output
  87. Batch Script — Input / Output
  88. Redirecting Output (Stdout and Stderr)
  89. Suppressing Program Output
  90. Stdin
  91. Batch Script — Return Code
  92. Error Level
  93. Syntax
  94. Example
  95. Output
  96. Loops
  97. Looping through Command Line Arguments
  98. Example
  99. Output
  100. Batch Script — Functions
  101. Function Definition
  102. Example
  103. Batch Script — Process
  104. Viewing the List of Running Processes
  105. Syntax
  106. Examples
  107. Killing a Particular Process
  108. Syntax
  109. Examples
  110. Starting a New Process
  111. Syntax
  112. Examples
  113. Batch Script — Aliases
  114. Creating an Alias
  115. Syntax
  116. Example
  117. Output
  118. Deleting an Alias
  119. Example
  120. Replacing an Alias
  121. Example
  122. Batch Script — Devices
  123. Syntax
  124. Examples
  125. Batch Script — Registry
  126. Batch Script — Network
  127. Batch Script — Printing
  128. Syntax
  129. Example
  130. Command Line Printer Control
  131. Syntax
  132. Testing if a Printer Exists
  133. Example
  134. Batch Script — Debugging
  135. Error Messages
  136. Complex Command Lines
  137. Subroutines
  138. Windows Versions
  139. Batch Script — Logging
  140. Syntax
  141. Example
  142. 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

  1. INI (*.ini) – Initialization file. These set the default variables for the system and programs.
  2. CFG (*.cfg) – These are the configuration files.
  3. SYS (*.sys) – System files, can sometimes be edited, mostly compiled machine code in new versions.
  4. 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.
  5. 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.

  • Validating input
    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.
  • Check variables before using them
    Always check the new variable before using them or initializing them because they might already have been defined.
  • Indentation
    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 — Files

    In this chapter, we will learn how to create, save, execute, and modify batch files.

    Creating Batch Files

    Batch 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 Files

    After 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.

    • Remember to put the .bat or .cmd at the end of the file name.
    • Choose the “Save as type” option as “All Files”.
    • Put the entire file name in quotes “”.

    Executing Batch Files

    Following 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 Files

    Following 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 — Syntax

    Normally, the first line in a batch file often consists of the following command.

    ECHO Command

    By 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.

    Documentation

    Very 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 Program

    Let’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 — Variables

    There 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 Arguments

    Batch 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 Command

    The other way in which variables can be initialized is via the ‘set’ command. Following is the syntax of the set command.

    Syntax

    variable-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.

    Example

    In 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.

    Output

    The above command produces the following output.

    Working with Numeric Values

    In 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 Variables

    In 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.

    Example

    Few 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.

    Output

    The 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 Variables

    If 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 — Comments

    It’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 Statement

    There 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.

    Syntax

    where ‘Remarks’ is the comments which needs to be added.

    The following example shows a simple way the Rem command can be used.

    Example

    Output

    The above command produces the following output. You will notice that the line with the Rem statement will not be executed.

    Comments Using the :: Statement

    The 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.

    Syntax

    where ‘Remarks’ is the comment which needs to be added.

    The following example shows a simple way the Rem command can be used.

    Example

    Output

    The 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 — Strings

    In DOS, a string is an ordered collection of characters, such as «Hello, World!».

    S.No Strings & Description
    1 Create String

    A string can be created in DOS in the following way.

    String interpolation is a way to construct a new String value from a mix of constants, variables, literals, and expressions by including their values inside a string literal.

    You can use the set operator to concatenate two strings or a string and a character, or two characters. Following is a simple example which shows how to use string concatenation.

    In DOS scripting, there is no length function defined for finding the length of a string. There are custom-defined functions which can be used for the same. Following is an example of a custom-defined function for seeing the length of a string.

    A variable which has been set as string using the set variable can be converted to an integer using the /A switch which is using the set variable. The following example shows how this can be accomplished.

    This used to align text to the right, which is normally used to improve readability of number columns.

    This is used to extract characters from the beginning of a string.

    This is used to extract a substring via the position of the characters in the string.

    The string substitution feature can also be used to remove a substring from another string.

    This is used to remove the first and the last character of a string.

    This is used to remove all spaces in a string via substitution.

    To replace a substring with another string use the string substitution feature.

    This is used to extract characters from the end of a string.

    Batch Script — Arrays

    Arrays are not specifically defined as a type in Batch Script but can be implemented. The following things need to be noted when arrays are implemented in Batch Script.

    • Each element of the array needs to be defined with the set command.
    • The ‘for’ loop would be required to iterate through the values of the array.

    Creating an Array

    An array is created by using the following set command.

    Where 0 is the index of the array and 1 is the value assigned to the first element of the array.

    Another way to implement arrays is to define a list of values and iterate through the list of values. The following example show how this can be implemented.

    Example

    Output

    The above command produces the following output.

    Accessing Arrays

    You can retrieve a value from the array by using subscript syntax, passing the index of the value you want to retrieve within square brackets immediately after the name of the array.

    Example

    In this example, the index starts from 0 which means the first element can be accessed using index as 0, the second element can be accessed using index as 1 and so on. Let’s check the following example to create, initialize and access arrays −

    The above command produces the following output.

    Modifying an Array

    To add an element to the end of the array, you can use the set element along with the last index of the array element.

    Example

    The above command produces the following output.

    You can modify an existing element of an Array by assigning a new value at a given index as shown in the following example −

    The above command produces the following output.

    Iterating Over an Array

    Iterating over an array is achieved by using the ‘for’ loop and going through each element of the array. The following example shows a simple way that an array can be implemented.

    Following things need to be noted about the above program −

    Each element of the array needs to be specifically defined using the set command.

    The ‘for’ loop with the /L parameter for moving through ranges is used to iterate through the array.

    Output

    The above command produces the following output.

    Length of an Array

    The length of an array is done by iterating over the list of values in the array since there is no direct function to determine the number of elements in an array.

    Output

    Output The above command produces the following output.

    Creating Structures in Arrays

    Structures can also be implemented in batch files using a little bit of an extra coding for implementation. The following example shows how this can be achieved.

    Example

    The following key things need to be noted about the above code.

    Each variable defined using the set command has 2 values associated with each index of the array.

    The variable i is set to 0 so that we can loop through the structure will the length of the array which is 3.

    We always check for the condition on whether the value of i is equal to the value of len and if not, we loop through the code.

    We are able to access each element of the structure using the obj[%i%] notation.

    Output

    The above command produces the following output.

    Batch Script — Decision Making

    Decision-making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.

    S.No Strings & Description
    1 If Statement

    The first decision-making statement is the ‘if’ statement.

    The next decision making statement is the If/else statement. Following is the general form of this statement.

    Sometimes, there is a requirement to have multiple ‘if’ statement embedded inside each other. Following is the general form of this statement.

    Batch Script — Operators

    An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations.

    In batch script, the following types of operators are possible.

    • Arithmetic operators
    • Relational operators
    • Logical operators
    • Assignment operators
    • Bitwise operators

    Arithmetic Operators

    Batch script language supports the normal Arithmetic operators as any language. Following are the Arithmetic operators available.

    Operator Description Example
    + Addition of two operands 1 + 2 will give 3
    Subtracts second operand from the first 2 − 1 will give 1
    * Multiplication of both operands 2 * 2 will give 4
    / Division of the numerator by the denominator 3 / 2 will give 1.5
    % Modulus operator and remainder of after an integer/float division 3 % 2 will give 1

    Relational Operators

    Relational operators allow of the comparison of objects. Below are the relational operators available.

    Operator Description Example
    EQU Tests the equality between two objects 2 EQU 2 will give true
    NEQ Tests the difference between two objects 3 NEQ 2 will give true
    LSS Checks to see if the left object is less than the right operand 2 LSS 3 will give true
    LEQ Checks to see if the left object is less than or equal to the right operand 2 LEQ 3 will give true
    GTR Checks to see if the left object is greater than the right operand 3 GTR 2 will give true
    GEQ Checks to see if the left object is greater than or equal to the right operand 3 GEQ 2 will give true

    Logical Operators

    Logical operators are used to evaluate Boolean expressions. Following are the logical operators available.

    The batch language is equipped with a full set of Boolean logic operators like AND, OR, XOR, but only for binary numbers. Neither are there any values for TRUE or FALSE. The only logical operator available for conditions is the NOT operator.

    Operator Description
    AND This is the logical “and” operator
    OR This is the logical “or” operator
    NOT This is the logical “not” operator

    Assignment Operators

    Batch Script language also provides assignment operators. Following are the assignment operators available.

    Output will be 8

    Output will be 2

    Output will be 15

    Output will be 2

    Output will be 2

    Bitwise Operators

    Bitwise operators are also possible in batch script. Following are the operators available.

    Operator Description Example
    += This adds right operand to the left operand and assigns the result to left operand
    -= This subtracts the right operand from the left operand and assigns the result to the left operand
    *= This multiplies the right operand with the left operand and assigns the result to the left operand
    /= This divides the left operand with the right operand and assigns the result to the left operand
    %= This takes modulus using two operands and assigns the result to the left operand
    Operator Description
    & This is the bitwise “and” operator
    | This is the bitwise “or” operator
    ^ This is the bitwise “xor” or Exclusive or operator

    Following is the truth table showcasing these operators.

    p q p & q p | q p ^ q
    0 0 0 0 0
    0 1 0 1 1
    1 1 1 1 0
    1 0 0 1 1

    Batch Script — DATE and TIME

    The date and time in DOS Scripting have the following two basic commands for retrieving the date and time of the system.

    This command gets the system date.

    Syntax

    Example

    Output

    The current date will be displayed in the command prompt. For example,

    This command sets or displays the time.

    Syntax

    Example

    Output

    The current system time will be displayed. For example,

    Following are some implementations which can be used to get the date and time in different formats.

    Date in Format Year-Month-Day

    Example

    Output

    The above command produces the following output.

    Batch Script — Input / Output

    There are three universal “files” for keyboard input, printing text on the screen and printing errors on the screen. The “Standard In” file, known as stdin, contains the input to the program/script. The “Standard Out” file, known as stdout, is used to write output for display on the screen. Finally, the “Standard Err” file, known as stderr, contains any error messages for display on the screen.

    Each of these three standard files, otherwise known as the standard streams, are referenced using the numbers 0, 1, and 2. Stdin is file 0, stdout is file 1, and stderr is file 2.

    Redirecting Output (Stdout and Stderr)

    One common practice in batch files is sending the output of a program to a log file. The > operator sends, or redirects, stdout or stderr to another file. The following example shows how this can be done.

    In the above example, the stdout of the command Dir C:\ is redirected to the file list.txt.

    If you append the number 2 to the redirection filter, then it would redirect the stderr to the file lists.txt.

    One can even combine the stdout and stderr streams using the file number and the ‘&’ prefix. Following is an example.

    Suppressing Program Output

    The pseudo file NUL is used to discard any output from a program. The following example shows that the output of the command DIR is discarded by sending the output to NUL.

    Stdin

    To work with the Stdin, you have to use a workaround to achieve this. This can be done by redirecting the command prompt’s own stdin, called CON.

    The following example shows how you can redirect the output to a file called lists.txt. After you execute the below command, the command prompt will take all the input entered by user till it gets an EOF character. Later, it sends all the input to the file lists.txt.

    Batch Script — Return Code

    By default when a command line execution is completed it should either return zero when execution succeeds or non-zero when execution fails. When a batch script returns a non-zero value after the execution fails, the non-zero value will indicate what is the error number. We will then use the error number to determine what the error is about and resolve it accordingly.

    Following are the common exit code and their description.

    Not enough virtual memory is available.

    It indicates that Windows has run out of memory.

    Error Code Description
    0 Program successfully completed.
    1 Incorrect function. Indicates that Action has attempted to execute non-recognized command in Windows command prompt cmd.exe.
    2 The system cannot find the file specified. Indicates that the file cannot be found in specified location.
    3 The system cannot find the path specified. Indicates that the specified path cannot be found.
    5 Access is denied. Indicates that user has no access right to specified resource.
    Program is not recognized as an internal or external command, operable program or batch file. Indicates that command, application name or path has been misspelled when configuring the Action.
    The application terminated as a result of a CTRL+C. Indicates that the application has been terminated either by the user’s keyboard input CTRL+C or CTRL+Break or closing command prompt window.
    The application failed to initialize properly. Indicates that the application has been launched on a Desktop to which the current user has no access rights. Another possible cause is that either gdi32.dll or user32.dll has failed to initialize.

    Error Level

    The environmental variable %ERRORLEVEL% contains the return code of the last executed program or script.

    By default, the way to check for the ERRORLEVEL is via the following code.

    Syntax

    It is common to use the command EXIT /B %ERRORLEVEL% at the end of the batch file to return the error codes from the batch file.

    EXIT /B at the end of the batch file will stop execution of a batch file.

    Use EXIT /B at the end of the batch file to return custom return codes.

    Environment variable %ERRORLEVEL% contains the latest errorlevel in the batch file, which is the latest error codes from the last command executed. In the batch file, it is always a good practice to use environment variables instead of constant values, since the same variable get expanded to different values on different computers.

    Let’s look at a quick example on how to check for error codes from a batch file.

    Example

    Let’s assume we have a batch file called Find.cmd which has the following code. In the code, we have clearly mentioned that we if don’t find the file called lists.txt then we should set the errorlevel to 7. Similarly, if we see that the variable userprofile is not defined then we should set the errorlevel code to 9.

    Let’s assume we have another file called App.cmd that calls Find.cmd first. Now, if the Find.cmd returns an error wherein it sets the errorlevel to greater than 0 then it would exit the program. In the following batch file, after calling the Find.cnd find, it actually checks to see if the errorlevel is greater than 0.

    Output

    In the above program, we can have the following scenarios as the output −

    If the file c:\lists.txt does not exist, then nothing will be displayed in the console output.

    If the variable userprofile does not exist, then nothing will be displayed in the console output.

    If both of the above condition passes then the string “Successful completion” will be displayed in the command prompt.

    Loops

    In the decision making chapter, we have seen statements which have been executed one after the other in a sequential manner. Additionally, implementations can also be done in Batch Script to alter the flow of control in a program’s logic. They are then classified into flow of control statements.

    S.No Loops & Description
    1 While Statement Implementation

    There is no direct while statement available in Batch Script but we can do an implementation of this loop very easily by using the if statement and labels.

    The «FOR» construct offers looping capabilities for batch files. Following is the common construct of the ‘for’ statement for working with a list of values.

    The ‘for’ statement also has the ability to move through a range of values. Following is the general form of the statement.

    Following is the classic ‘for’ statement which is available in most programming languages.

    Looping through Command Line Arguments

    The ‘for’ statement can also be used for checking command line arguments. The following example shows how the ‘for’ statement can be used to loop through the command line arguments.

    Example

    Output

    Let’s assume that our above code is stored in a file called Test.bat. The above command will produce the following output if the batch file passes the command line arguments of 1,2 and 3 as Test.bat 1 2 3.

    S.No Loops & Description
    1 Break Statement Implementation

    The break statement is used to alter the flow of control inside loops within any programming language. The break statement is normally used in looping constructs and is used to cause immediate termination of the innermost enclosing loop.

    Batch Script — Functions

    A function is a set of statements organized together to perform a specific task. In batch scripts, a similar approach is adopted to group logical statements together to form a function.

    As like any other languages, functions in Batch Script follows the same procedure −

    Function Declaration − It tells the compiler about a function’s name, return type, and parameters.

    Function Definition − It provides the actual body of the function.

    Function Definition

    In Batch Script, a function is defined by using the label statement. When a function is newly defined, it may take one or several values as input ‘parameters’ to the function, process the functions in the main body, and pass back the values to the functions as output ‘return types’.

    Every function has a function name, which describes the task that the function performs. To use a function, you «call» that function with its name and pass its input values (known as arguments) that matches the types of the function’s parameters.

    Following is the syntax of a simple function.

    The function_name is the name given to the function which should have some meaning to match what the function actually does.

    The EXIT statement is used to ensure that the function exits properly.

    Following is an example of a simple function.

    Example

    S.No Functions & Description
    1 Calling a Function

    A function is called in Batch Script by using the call command.

    Functions can work with parameters by simply passing them when a call is made to the function.

    Functions can work with return values by simply passing variables names

    Local variables in functions can be used to avoid name conflicts and keep variable changes local to the function.

    The ability to completely encapsulate the body of a function by keeping variable changes local to the function and invisible to the caller.

    In Batch Script, it is possible to perform the normal file I/O operations that would be expected in any programming language.

    The creation of a new file is done with the help of the redirection filter >. This filter can be used to redirect any output to a file.

    Content writing to files is also done with the help of the redirection filter >. This filter can be used to redirect any output to a file.

    Content writing to files is also done with the help of the double redirection filter >>. This filter can be used to append any output to a file.

    Reading of files in a batch script is done via using the FOR loop command to go through each line which is defined in the file that needs to be read.

    For deleting files, Batch Script provides the DEL command.

    For renaming files, Batch Script provides the REN or RENAME command.

    For moving files, Batch Script provides the MOVE command.

    The pipe operator (|) takes the output (by default, STDOUT) of one command and directs it into the input (by default, STDIN) of another command.

    When a batch file is run, it gives you the option to pass in command line parameters which can then be read within the program for further processing.

    One of the limitations of command line arguments is that it can accept only arguments till %9. Let’s take an example of this limitation.

    In Batch Script, it is possible to perform the normal folder based operations that would be expected in any programming language.

    The creation of a folder is done with the assistance of the MD (Make directory) command.

    The listing of folder contents can be done with the dir command. This command allows you to see the available files and directories in the current directory.

    For deleting folders, Batch Scripting provides the DEL command.

    For renaming folders, Batch Script provides the REN or RENAME command.

    For moving folders, Batch Script provides the MOVE command.

    Batch Script — Process

    In this chapter, we will discuss the various processes involved in Batch Script.

    Viewing the List of Running Processes

    In Batch Script, the TASKLIST command can be used to get the list of currently running processes within a system.

    Syntax

    Specifies the remote system to connect to

    Specifies the user context under which the command should execute.

    Specifies the password for the given user context. Prompts for input if omitted.

    Lists all tasks currently using the given exe/dll name. If the module name is not specified all loaded modules are displayed.

    Displays services hosted in each process.

    Displays verbose task information.

    Displays a set of tasks that match a given criteria specified by the filter.

    Specifies the output format. Valid values: «TABLE», «LIST», «CSV».

    Specifies that the «Column Header» should not show in the output. Valid only for «TABLE» and «CSV» formats.

    Examples

    The above command will get the list of all the processes running on your local system. Following is a snapshot of the output which is rendered when the above command is run as it is. As you can see from the following output, not only do you get the various processes running on your system, you also get the memory usage of each process.

    The above command takes the output displayed by tasklist and saves it to the process.txt file.

    The above command will only fetch those processes whose memory is greater than 40MB. Following is a sample output that can be rendered.

    Killing a Particular Process

    Allows a user running Microsoft Windows XP professional, Windows 2003, or later to kill a task from a Windows command line by process id (PID) or image name. The command used for this purpose is the TASKILL command.

    Syntax

    Specifies the remote system to connect to

    Specifies the user context under which the command should execute.

    Specifies the password for the given user context. Prompts for input if omitted.

    Applies a filter to select a set of tasks. Allows «*» to be used. ex. imagename eq acme* See below filters for additional information and examples.

    Specifies the PID of the process to be terminated. Use TaskList to get the PID.

    Specifies the image name of the process to be terminated. Wildcard ‘*’ can be used to specify all tasks or image names.

    Terminates the specified process and any child processes which were started by it.

    Specifies to forcefully terminate the process(es).

    Examples

    The above command kills the open notepad task, if open.

    The above command kills a process which has a process of 9214.

    Starting a New Process

    DOS scripting also has the availability to start a new process altogether. This is achieved by using the START command.

    Syntax

    title − Text for the CMD window title bar (required.)

    path − Starting directory.

    command − The command, batch file or executable program to run.

    parameters − The parameters passed to the command.

    Following are the description of the options which can be presented to the START command.

    Start window Minimized

    Start window maximized.

    Use IDLE priority class.

    Use NORMAL priority class.

    Use ABOVENORMAL priority class.

    Use BELOWNORMAL priority class.

    Use HIGH priority class.

    Use REALTIME priority class.

    Examples

    The above command will run the batch script test.bat in a new window. The windows will start in the minimized mode and also have the title of “Test Batch Script”.

    The above command will actually run Microsoft word in another process and then open the file TESTA.txt in MS Word.

    Batch Script — Aliases

    Aliases means creating shortcuts or keywords for existing commands. Suppose if we wanted to execute the below command which is nothing but the directory listing command with the /w option to not show all of the necessary details in a directory listing.

    Suppose if we were to create a shortcut to this command as follows.

    When we want to execute the dir /w command, we can simply type in the word dw. The word ‘dw’ has now become an alias to the command Dir /w.

    Creating an Alias

    Alias are managed by using the doskey command.

    Syntax

    macroname − A short name for the macro.

    text − The commands you want to recall.

    Following are the description of the options which can be presented to the DOSKEY command.

    Installs a new copy of Doskey

    Sets size of command history buffer.

    Displays all Doskey macros.

    Displays all Doskey macros for all executables which have Doskey macros.

    Displays all Doskey macros for the given executable.

    Displays all commands stored in memory.

    Specifies that new text you type is inserted in old text.

    Specifies that new text overwrites old text.

    Specifies the executable.

    Specifies a file of macros to install.

    Specifies a name for a macro you create.

    Specifies commands you want to record.

    Example

    Create a new file called keys.bat and enter the following commands in the file. The below commands creates two aliases, one if for the cd command, which automatically goes to the directory called test. And the other is for the dir command.

    Once you execute the command, you will able to run these aliases in the command prompt.

    Output

    The following screenshot shows that after the above created batch file is executed, you can freely enter the ‘d’ command and it will give you the directory listing which means that your alias has been created.

    Deleting an Alias

    An alias or macro can be deleted by setting the value of the macro to NULL.

    Example

    In the above example, we are first setting the macro d to d = dir. After which we are setting it to NULL. Because we have set the value of d to NULL, the macro d will deleted.

    Replacing an Alias

    An alias or macro can be replaced by setting the value of the macro to the new desired value.

    Example

    In the above example, we are first setting the macro d to d = dir. After which we are setting it to dir /w. Since we have set the value of d to a new value, the alias ‘d’ will now take on the new value.

    Batch Script — Devices

    Windows now has an improved library which can be used in Batch Script for working with devices attached to the system. This is known as the device console – DevCon.exe.

    Windows driver developers and testers can use DevCon to verify that a driver is installed and configured correctly, including the proper INF files, driver stack, driver files, and driver package. You can also use the DevCon commands (enable, disable, install, start, stop, and continue) in scripts to test the driver. DevCon is a command-line tool that performs device management functions on local computers and remote computers.

    Display driver and device info DevCon can display the following properties of drivers and devices on local computers, and remote computers (running Windows XP and earlier) −

    Hardware IDs, compatible IDs, and device instance IDs. These identifiers are described in detail in device identification strings.

    Device setup classes.

    The devices in a device setup class.

    INF files and device driver files.

    Details of driver packages.

    Expected driver stack.

    Third-party driver packages in the driver store.

    Search for devices DevCon can search for installed and uninstalled devices on a local or remote computer by hardware ID, device instance ID, or device setup class.

    Change device settings DevCon can change the status or configuration of Plug and Play (PnP) devices on the local computer in the following ways −

    Enable a device.

    Disable a device.

    Update drivers (interactive and non-interactive).

    Install a device (create a devnode and install software).

    Remove a device from the device tree and delete its device stack.

    Rescan for Plug and Play devices.

    Add, delete, and reorder the hardware IDs of root-enumerated devices.

    Change the upper and lower filter drivers for a device setup class.

    Add and delete third-party driver packages from the driver store.

    DevCon (DevCon.exe) is included when you install the WDK, Visual Studio, and the Windows SDK for desktop apps. DevCon.exe kit is available in the following locations when installed.

    Syntax

    /m:\\computer − Runs the command on the specified remote computer. The backslashes are required.

    /r − Conditional reboot. Reboots the system after completing an operation only if a reboot is required to make a change effective.

    command − Specifies a DevCon command.

    To list and display information about devices on the computer, use the following commands −

    To search for information about devices on the computer, use the following commands −

    To manipulate the device or change its configuration, use the following commands −

    Examples

    Following are some examples on how the DevCon command is used.

    The following command uses the DevCon DriverFiles operation to list the file names of drivers that devices on the system use. The command uses the wildcard character (*) to indicate all devices on the system. Because the output is extensive, the command uses the redirection character (>) to redirect the output to a reference file, driverfiles.txt.

    The following command uses the DevCon status operation to find the status of all devices on the local computer. It then saves the status in the status.txt file for logging or later review. The command uses the wildcard character (*) to represent all devices and the redirection character (>) to redirect the output to the status.txt file.

    The following command enables all printer devices on the computer by specifying the Printer setup class in a DevCon Enable command. The command includes the /r parameter, which reboots the system if it is necessary to make the enabling effective.

    The following command uses the DevCon Install operation to install a keyboard device on the local computer. The command includes the full path to the INF file for the device (keyboard.inf) and a hardware ID (*PNP030b).

    The following command will scan the computer for new devices.

    The following command will rescan the computer for new devices.

    Batch Script — Registry

    The Registry is one of the key elements on a windows system. It contains a lot of information on various aspects of the operating system. Almost all applications installed on a windows system interact with the registry in some form or the other.

    The Registry contains two basic elements: keys and values. Registry keys are container objects similar to folders. Registry values are non-container objects similar to files. Keys may contain values or further keys. Keys are referenced with a syntax similar to Windows’ path names, using backslashes to indicate levels of hierarchy.

    This chapter looks at various functions such as querying values, adding, deleting and editing values from the registry.

    S.No. Options & Description
    1.
    S.No Types of Registry & Description
    1 Reading from the Registry

    Reading from the registry is done via the REG QUERY command.

    Adding to the registry is done via the REG ADD command.

    Deleting from the registry is done via the REG DEL command.

    Copying from the registry is done via the REG COPY command.

    Comparing registry keys is done via the REG COMPARE command.

    Batch Script — Network

    Batch script has the facility to work with network settings. The NET command is used to update, fix, or view the network or network settings. This chapter looks at the different options available for the net command.

    S.No NET Commands & Description
    1 NET ACCOUNTS

    View the current password & logon restrictions for the computer.

    Displays your current server or workgroup settings.

    Adds or removes a computer attached to the windows domain controller.

    This command can be used for the following

    View the details of a particular user account.

    This command is used to stop and start a particular service.

    Display network statistics of the workstation or server.

    Connects or disconnects your computer from a shared resource or displays information about your connections.

    Batch Script — Printing

    Printing can also be controlled from within Batch Script via the NET PRINT command.

    Syntax

    Where /D:device — Specifies a print device.

    Example

    The above command will print the example.txt file to the parallel port lpt1.

    Command Line Printer Control

    As of Windows 2000, many, but not all, printer settings can be configured from Windows’s command line using PRINTUI.DLL and RUNDLL32.EXE

    Syntax

    Where some of the options available are the following −

    /dl − Delete local printer.

    /dn − Delete network printer connection.

    /dd − Delete printer driver.

    /e − Display printing preferences.

    /f[file] − Either inf file or output file.

    /F[file] − Location of an INF file that the INF file specified with /f may depend on.

    /ia − Install printer driver using inf file.

    /id − Install printer driver using add printer driver wizard.

    /if − Install printer using inf file.

    /ii − Install printer using add printer wizard with an inf file.

    /il − Install printer using add printer wizard.

    /in − Add network printer connection.

    /ip − Install printer using network printer installation wizard.

    /k − Print test page to specified printer, cannot be combined with command when installing a printer.

    /l[path] − Printer driver source path.

    /m[model] − Printer driver model name.

    /n[name] − Printer name.

    /o − Display printer queue view.

    /p − Display printer properties.

    /Ss − Store printer settings into a file.

    /Sr − Restore printer settings from a file.

    /y − Set printer as the default.

    /Xg − Get printer settings.

    /Xs − Set printer settings.

    Testing if a Printer Exists

    There can be cases wherein you might be connected to a network printer instead of a local printer. In such cases, it is always beneficial to check if a printer exists in the first place before printing.

    The existence of a printer can be evaluated with the help of the RUNDLL32.EXE PRINTUI.DLL which is used to control most of the printer settings.

    Example

    The above command will do the following −

    It will first set the printer name and set a file name which will hold the settings of the printer.

    The RUNDLL32.EXE PRINTUI.DLL commands will be used to check if the printer actually exists by sending the configuration settings of the file to the file Prt.txt

    Batch Script — Debugging

    Very often than not you can run into problems when running batch files and most often than not you would need to debug your batch files in some way or the other to determine the issue with the batch file itself. Following are some of the techniques that can help in debugging Batch Script files.

    Error Messages

    To discover the source of the message, follow these steps −

    Step 1 − REM out the @ECHO OFF line, i.e. REM @ECHO OFF or :: @ECHO OFF.

    Step 2 − Run the batch file with the required command line parameters, redirecting all output to a log file for later comparison.

    Step 3 − Search the file batch.log for the error messages

    Step 4 − Check the previous line for any unexpected or invalid command, command line switch(es) or value(s); pay special attention to the values of any environment variables used in the command.

    Step 5 − Correct the error and repeat this process until all error messages have disappeared.

    Complex Command Lines

    Another common source of errors are incorrectly redirected commands, like for example «nested» FIND or FINDSTR commands with incorrect search strings, sometimes within a FOR /F loop.

    To check the validity of these complex commands, follow these steps −

    Step 1 − Insert «command check lines» just before a line which uses the complex command set.

    Following is an example wherein the ECHO command is inserted to mark where the output of the first TYPE command ends and the next one starts.

    Step 2 − Follow the procedure to find error message sources described above.

    Step 3 − Pay special attention to the output of the «simplified» command lines: Is the output of the expected format? Is the «token» value or position as expected?

    Subroutines

    Subroutines generating error messages pose an extra «challenge» in finding the cause of the error, as they may be called multiple times in the same batch file.

    To help find out what causes the incorrect call to the subroutine, follow these steps −

    Step 1 − Add and reset a counter variable at the beginning of the script −

    Step 2 − Increment the counter each time the subroutine is called, by inserting the following line at the beginning of the subroutine

    Step 3 − Insert another line right after the counter increment, containing only the SET command; this will list all environment variables and their values.

    Step 4 − Follow the procedure to find error message sources described above.

    Windows Versions

    If you intend to distribute your batch files to other computers that may or may not run the same Windows version, you will need to test your batch files in as many Windows versions as possible.

    The following example shows how to check for various operating system versions to check the relevant windows versions.

    Batch Script — Logging

    Logging in is possible in Batch Script by using the redirection command.

    Syntax

    Example

    Create a file called test.bat and enter the following command in the file.

    The above command has an error because the option to the net statistics command is given in the wrong way.

    Output

    If the command with the above test.bat file is run as

    And you open the file testerrors.txt, you will see the following error.

    The syntax of this command is −

    More help is available by typing NET HELPMSG 3506.

    Читайте также:  Sketchup mac os big sur
    Оцените статью