Windows Batch File Programming

  1. Windows Batch File Programming Pdf
  2. Windows Batch File Programming Examples
  3. Windows Batch File Programming Language
  4. Windows Batch File Programming Tutorial
  5. Batch Programming Tutorials

Batch file programming is the native programming offered by the Microsoft Windows Operating System. Batch file is created using any text editors like notepad, WordPad, WinWord or so on, which comprises of a sequence of built-in commands used to perform some often done tasks like deleting a. Description: This DOS batch guide brings structure into your DOS script by using real function like constructs within a DOS batch file. It offers a DOS function collection, tutorials and examples, plus a forum to discuss related topics. To create a Batch file, you have to write the command as text in Notepad, and save the file as a.bat file. To execute a command, you simply need to double-click the batch file. Hence, a well-written batch file in Windows can save a lot of time. Some basic Commands in Batch Files: ECHO: To display the text on the screen. 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. The instructions in batch files are for automating repetitive command sequences. Batch files can be used to store a series of commands which can then used by the command line interpreter CMD as an input. As we know, CMD or Command Prompt can take various commands as input and processes them. To enter the command we open CMD and type the commands directly. The thing is, we. Read moreHow To Create A Batch File in Windows 10. I update my webpage everyday so I decided to create a batch file to start this program automatically at startup so it is always ready for me to use. Here’s how to write a simple batch file to start a program when you start your computer: Open notepad. It is located at Start MenuAll ProgramsAccessoriesNotepad (Windows XP).

< Windows Programming

In Windows NT (XP, Vista, 7, 8, 10,...) one is able to write batch files that are interpreted by the Command Prompt (cmd.exe). They can be used to automate file-system tasks such as backups or basic installations and can be used with other command-line utilities as well. The batch files can be considered to be a simple scripting language with logic and jumps. The advantages of using batch files are the ease of writing them, the ability to edit the files without compiling anything, their cross-compatibility across Windows NT Operating Systems and their inherent ability to manipulate file systems due to their basis on MS-DOS. Batch file scripts are not case-sensitive, although strings and data are. The file is controlled by a list of commands separated into lines which are run like normal commands would be at the Command Prompt, although some functionality is different. Batch files can be run from Windows Explorer but the console used to display them closes automatically at the end of the batch file, so a command at the end that prevents instantaneous exit is needed for any remaining output to be read before the console window closes. Although the batch files are able to manipulate their environment, such as color settings and environment variables, the changes are all temporary, as in a standard Command Prompt session. Color settings, however, are retained on later editions of Windows NT. In order to try to learn about batch files, it is useful to understand Command Prompt commands. See: Guide to Windows commands.

  • 7Flow Control
    • 7.1Conditionals

Batch File[edit]

The script is kept inside a batch file, with the extension .bat or .cmd. Although .bat is more recognisable, as it was used in the MS-DOS environment that preceded the Command Prompt, the Command Prompt's interpretations of batch files is very different to the manner of interpreting DOS batch files, and .cmd files are only interpreted by the Command Prompt, so using the .cmd extension prevents mis-use in older environments.

Execution starts at the top of the file and ends at the end. When the end of the file is reached, the file exits to the Command Prompt if it was invoked from there, or the console window closes if it was invoked from Windows Explorer or the START command.

ECHO Command[edit]

Typically, batch files start with the 'echo off' command, which stops the input and prompt from being displayed during execution, so only the command output is displayed. The '@' symbol prevents a command from having input and its prompt displayed. It is used on the 'echo off' command to prevent that first command from displaying the input and prompt:

In order to print lines, the ECHO command is used again, but this time with a text parameter other than 'off':

The period ('.') is used to prevent confusion with the attempt to output ON or OFF rather than turn input and prompt displaying on and off. The last line in a code should then be:

'Echo on' will turn the input/prompt display back on, just in case the program exits to the Command Prompt where without the command 'echo on', there will be no visible prompt left for use.

HINT: Starting with Windows XP, the ECHO ON command is optional. The command interpreter automatically enables it after the BAT file terminates.

Hello World Example[edit]

Using the code above, we can make a hello world program like so:

Comments[edit]

In batch files there are two ways of writing comments. Firstly there is the form:

This form is included as it was in the MS-DOS batch file script. The other form is this:

This form is generally favoured, for being faster to execute and write, and also for being easy to differentiate from normal commands. For this type of comment only two double-colons ('::') are needed and the comment ends at the end of the line. Batch files have no multi-line comment types.

You can also add a comment to the end of the command:

Variables[edit]

We access variables with the SET command. SET lets us set the value for a variable, and delete a variable. The variables used are environment variables, which are set up to correspond to the system's environment variables, although they are not the actual environment variables of the system and changing them will not change system environment variables. For example:

This command creates an environment variable called name, and sets its value to the string 'John Smith'. The first space is ignored as the value entered records from the first non-whitespace character encountered after the '=' sign.

'Set' also allows the storing of integers specifically, using the /A parameter:

This command creates an environment variable named number with the integer value 38, not the string value '38'. This number can be involved in arithmetic and numerical logic, but without the /A parameter all that is stored are the characters '3' and '8', which can't be used as numbers.

Variables are accessed by surrounding the name with '%'s. This substitutes the value straight into a command, and does not point to the variable. For example:

This file would return the text 'John Smith'. A string number can be converted to an integer number in a similar fashion:

This code creates a string called num, then overwrites it with an integer with the numerical value represented by the string contents of num, in this case 38. 'num' is now an integer number ready for use as a number.

Input[edit]

The set command can also be used for input:

This command displays 'Enter a value for var:' and when the user enters the data, var is given that value.

Be aware, if the user presses enter without entering anything then the value in var is unchanged, so for the sake of a prompt it is often best to give a default value, or clear the value for the variable first if it has been used before:

Below is an example:

This batch file gets the name of a file to delete and then uses the DEL command with the prompt parameter '/P' to ask the user if they're sure they want to delete the file.

Flow Control[edit]

Conditionals[edit]

IF[edit]

The IF command can be used to create program logic in batch files. The IF command allows three basic checks, on the ERRORLEVEL, the equality of two strings, and the existence of a file or folder. The first check on the ERRORLEVEL will check to see if it is greater than or equal to a certain number:

For this style the first parameter is always ERRORLEVEL, and the second is the value it checks against. In this case, if the ERRORLEVEL is at least 5 then the command at the end of the line is executed, outputting the message 'The ERRORLEVEL is at least 5.'. The second form is a check between two strings:

Here the first parameter is two strings either side of the double '=', symbolising a check to see if they are equal. If the variable str1 is exactly equal to 'Hello.', a check which is case-sensitive, then 'The strings are equal.' is outputted. In the case that you wish to make the check case-insensitive you would rewrite it as following:

Now, for example, str1 could contain 'HELLO.' but the check would still result in the command being executed at the end as the check is now case-insensitive. The final basic IF type is the existence check, to see if a file or folder exists.

Windows Batch File Programming

Here if the file 'myfile.txt' exists in the current folder then the command TYPE myfile.txt is executed which displays the contents of 'myfile.txt' in the console window.

All of the preceding examples have an optional NOT parameter that can be written after the IF which will execute the command at the end of the line if the condition is not true. For example:

Which will output 'File missing.' if the file 'myfile.txt' is not existent in the current folder. There are a few other IF types with command extensions, which can be seen with the IF /? command at the command prompt.

ELSE[edit]

The ELSE operator can be used with a combination of brackets to provide multi-line logical statements that provide an alternative set of commands if the condition is not true.

Unlike some languages, in batch files the scripting requires that the lines IF condition (, ) ELSE ( and ) are written very specifically like that. It is possible, however, to re-write it to use single-line outcomes all on one line:

Below is an example of the ELSE operator in use:

This batch file will delete a file, unless it doesn't exist in which case it will tell you with the message 'ERROR: %answer% can not be found in this folder!'.

Unlike in most computer languages, multiple multi-line IF...ELSE style statements can't be nested in batch files.

Jumps[edit]

You can control program flow using the GOTO statement. Batch files don't have all elements for structured programming scripting, however some elements of structured programming such as functions can be simulated. The simplest way of controlling program flow, however, is the GOTO statement which jumps to a specified label.

Namir

This code will direct program flow to the label labelnam, which is found at the first occurance of this line:

It is important to remember that labels only store 8 characters, so if a label is longer than 8 characters only the first 8 will be seen. This means the labels labelname1 and labelname2 can't be distinguished from each other as their only difference occurs past the first 8 characters. Although not strictly incorrect, it is better to avoid using label names longer than 8 characters to avoid these distinguishing problems easily.

Here is the example from earlier redesigned to loop until asked to stop:

Take note of the command GOTO :EOF. This command will take the script to the end of the file and end the current batch script.

Windows Batch File Programming Pdf

FOR Looping[edit]

Runs a specified command for each file in a set of files.

To use the FOR command in a batch program, specify %%variable insteadof %variable. Variable names are case sensitive, so %i is differentfrom %I.

Batch File Example:

This command will list all the files ending in .txt in the current directory.

If Command Extensions are enabled, the following additionalforms of the FOR command are supported:

If set contains wildcards, then specifies to match against directorynames instead of file names.

Walks the directory tree rooted at [drive:]path, executing the FORstatement in each directory of the tree. If no directoryspecification is specified after /R then the current directory isassumed. If set is just a single period (.) character then itwill just enumerate the directory tree.

The set is a sequence of numbers from start to end, by step amount.So (1,1,5) would generate the sequence 1 2 3 4 5 and (5,-1,1) wouldgenerate the sequence (5 4 3 2 1)

or, if usebackq (or useback) option present:

(The purpose of usebackq is to use a fullname of file-set including the space.)

filenameset is one or more file names. Each file is opened, readand processed before going on to the next file in filenameset.Processing consists of reading in the file, breaking it up intoindividual lines of text and then parsing each line into zero ormore tokens. The body of the for loop is then called with thevariable value(s) set to the found token string(s). By default, /Fpasses the first blank separated token from each line of each file.Blank lines are skipped. You can override the default parsingbehavior by specifying the optional 'options' parameter. Thisis a quoted string which contains one or more keywords to specifydifferent parsing options. The keywords are:

Windows Batch File Programming Examples

Some examples might help:

would parse each line in myfile.txt, ignoring lines that begin witha semicolon, passing the 2nd and 3rd token from each line to the forbody, with tokens delimited by commas and/or spaces. Notice the forbody statements reference %i to get the 2nd token, %j to get the3rd token, and %k to get all remaining tokens after the 3rd. Forfile names that contain spaces, you need to quote the filenames withdouble quotes. In order to use double quotes in this manner, you alsoneed to use the usebackq option, otherwise the double quotes will beinterpreted as defining a literal string to parse.

%i is explicitly declared in the for statement and the %j and %kare implicitly declared via the tokens= option. You can specify upto 26 tokens via the tokens= line, provided it does not cause anattempt to declare a variable higher than the letter 'z' or 'Z'.Remember, FOR variables are single-letter, case sensitive, global, and you can't have more than 52 total active at any one time.

You can also use the FOR /F parsing logic on an immediate string, bymaking the filenameset between the parenthesis a quoted string,using single quote characters. It will be treated as a single lineof input from a file and parsed.

Finally, you can use the FOR /F command to parse the output of acommand. You do this by making the filenameset between theparenthesis a back quoted string. It will be treated as a commandline, which is passed to a child CMD.EXE and the output is capturedinto memory and parsed as if it was a file. So the followingexample:

would enumerate the environment variable names in the currentenvironment.

In addition, substitution of FOR variable references has been enhanced.You can now use the following optional syntax:

The modifiers can be combined to get compound results:

In the above examples %I and PATH can be replaced by other validvalues. The %~ syntax is terminated by a valid FOR variable name.Picking upper case variable names like %I makes it more readable andavoids confusion with the modifiers, which are not case sensitive.

Pipes[edit]

this is mainly used to redirect the output of one program to another program

means execute 'a' and what all output 'a' gives to the console - give that as 'b' s input

will give a list of file which contain '.htm' in their names

The output of a command as well as possible errors could be redirected also to files (Note the 2 in front of the >> ):

Functions[edit]

Functions may be simulated by using labels to control flow of execution, and using an environment variable to return the resulting return value. Labels can be defined at any place in the script and do not need to be referenced. The code following the label will be executed when encountered. Code blocks identified by labels are usually most conveniently placed after the main script has exited (at the end of the file) so that they will not run accidentally, but will be reached only when targeted by a GOTO or CALL statement.

The subroutine construct works because of the following:

  • Code identified by a label can be jumped to by using the GOTO built in command
  • Using the CALL built in command with a label creates a new invocation of the command processor for the same script, with an implicit GOTO the label
  • Using the expression GOTO :EOF closes the current command processor invocation (Same as EXIT /B except the latter allows to specify an ERRORLEVEL)

The structure of a subroutine call looks like this:

Windows Batch File Programming Language


Bat file with next content outputs '42' as result of execution

Note:

  • Using CALL with a label or the expression CALL :EOF or EXIT /B requires command extensions to be enabled.
  • A label is a line consisting of a valid name (not containing any separators such as space or semicolon) prefixed by a colon.

Command-Line Interfacing[edit]

let's say we want to call a program 'MyProgram' from the command prompt. we type the following into our prompt (the .exe file extension is unnecessary):

And this will run the myprogram executable. Now, let's say we want to pass a few arguments to this program:

Now, if we go into the standard main function, we will have our argc and argv values:

Where:

This shouldn't come as a big surprise to people who have any familiarity with standard C programming. However, if we translate this to our WinMain function, we get a different value:

we will only have one value to accept the command line:

We can also use the function GetCommandLine to retrieve this string from any point in the application. If we want to parse this into a standard argv/argc pair, we can use the function CommandLineToArgvW to perform the conversion. It is important to note that CommandLineToArgvW only works on unicode strings.

When we return a value from our C program, that value gets passed to the CMD shell, and stored in a variable called 'ERRORLEVEL'. ERRORLEVEL is the only global variable that is not a string, and it can contain a number from 0 to 255. By convention, a value of zero means 'success', while a value other then zero signifies an error.

Windows Batch File Programming Tutorial

Let's say we wanted to write a C program that returns the number of arguments passed to it. This might sound like a simple task in C, but it is difficult to accomplish in batch script:

And we will name this program 'CountArgs.exe'. Now, we can put this into a batch script, to pass it a number of arguments, and to print out the number passed:

We can, in turn, call this script 'count.bat', and run that from a command prompt:

and running this will return the answer: 3.

Batch Programming Tutorials

NOTE: Actually, this can be accomplished with a batch file without resorting to a C program, by simply using CMD delayed variable expansion via the '/V:ON' parameter:

Then use a simple batch file like the following to count parameters:

Or an easier way, without having to enable & use 'delayed environment expansion', would be to do the following:


This returns the same answer as the C program example.

Console Control Handlers[edit]

Retrieved from 'https://en.wikibooks.org/w/index.php?title=Windows_Programming/Programming_CMD&oldid=3580566'