BATCH Explanations: Third Edition By FAMICOMASTER / VCSMaster, 2019 - 2020 0.0 Introductions 0.1 Introducing the script 0.2 Prerequisites 0.3 Document formatting 1.0 The Basics 1.1 File names 1.2 Initialization 1.3 Variables 1.3b Special variables 1.4 Basic Window controls 1.5 Basic Text controls 1.6 Basic File controls 1.7 Data redirection 1.8 Speed control 2.0 The Next Level 2.1 Random numbers 2.1b Random number selectivity 2.2 Flow control 2.3 Conditional statements 2.4 Instant key presses 2.5 Extracting other files 2.6 Advanced Text controls 2.7 Advanced File controls Section 0.0 Introductions Part 0.1 Introducing the script So, you want to learn how to Batch like a pro? Do you want to automate your tasks, write simple games, maybe something more advanced, even? Well, you're in the right place, my friend, because this document will teach you everything you need to know to script with the best of them! There are a couple reasons you might wish to choose a Batch script over a more complicated language: -Much smaller files compared to C languages, including Java and Python -No IDE, compiler, or other special programs required to write and run -Simpler to learn and master than most languages -Minimal performance troubles caused by sloppy programming for beginners -Massive user base, anyone with a Windows NT machine and run your scripts! Part 0.2 Prerequisites Batch does not have many specific prerequisites for making and running your scripts, but there are still a few to beware of: -Intel Pentium at 133MHz or faster -64MB or more RAM -1GB or more of free uncompressed hard disk space -Windows 2000 Service Pack 2o or later -An internet connection These are the bare minimum requirements to write most scripts. Many fairly complex games that I've written myself will run on a system of this caliber no problem. However, there are a few cases where you might want more. Some things you might be interested in having include: -A fast CPU if you are doing a lot of calculations -More RAM for large programs and multitasking -More disk space for data storage -Windows 7 or later for a few nice extensions Part 0.3 Document formatting I will try to keep this document formatted and organized well. Here are a few types of annotations I will use to make mention of things. When a section is annotated as +text+, it means that there are some extras you may want. When a section is annotated as (text), it means that you should insert your own text here without the parenthesis. When a section is annotated as [text], it means that you should insert the name of a variable here, without the brackets. When a section is annotated as {text}, it means that you should insert another command here, without the braces. Section 1.0 The Basics Part 1.1 File names Before starting to write your program, you should consider a file name. Well, duh, of course you should. "But isn't that obvious?" I hear you say. Well yes, but Batch scripts have a few things you might want to keep in mind! -Try to have a short file name, 8 characters is an ideal length, although you can have more, of course. -Avoid special characters or spaces if at all possible. This can make some things difficult. -Keep your file name extensions to 3 characters or less! This is important for compatibility reasons. There are two types of Batch files: BAT and CMD. A .BAT file can be run in almost any Microsoft operating system, from DOS all the way up to Windows 10. This mode has the most compatibility, but it also means that users could accidentally run your script on an incompatible operating system! On the other hand, a .CMD file will only run in Windows NT based operating systems, which begins with NT4 and ends up at Windows 10. This is an ideal setup because it should mean that only machines capable of running the contents of your script will be able to even open and start it. Part 1.2 Initialization At the beginning of every program, you should probably set up a few things. The first of these is to disable command echoing. Command echoing puts the directory of your script and the command being executed on every line of the screen. This is not what you want, excluding for debug purposes. To turn command echoing off, add the following line to your program: @ECHO OFF The command "ECHO" with the text "ON" or "OFF" will enable or disable command echoing. Executing the command ECHO by itself, with no operand, will display whether or not command echoing is enabled. The "at" symbol (@) is used to disable command echoing for one line. Using both of these in conjunction, you can keep your screen clean on start up, although it is usually best to clear the screen after anyways. For some more complex programs, you may also want to enable Delayed Expansions, which we will talk about in more detail later. To enable (or disable) this function, at the start of your script you will want to include one of the following lines: SETLOCAL EnableDelayedExpansions SETLOCAL DisableDelayedExpansions Because of the way the SETLOCAL command works, you probably want to put this very near the beginning of your script if you are going to include it at all. Part 1.3 Variables Variables are the most important concept in programming. A variable is a cell which can hold a given value. In some programming languages, variables have types. Batch is not one of these languages. Any variable in a Batch script can hold any value if it is assigned properly. Variables are created and modified with the "SET" command. It's syntax is as follows: SET [Variable]=(Some text) SET /A [Variable]=(Mathematical expression or a number) SET /P [Variable]=(A prompt for the user) As you can see, there are three variations of the SET command. Without a switch, SET will direct the data after the equals sign into the variable you named. With the switch /A, Batch will attempt to perform arithmetic before storing the data. With the switch /P, Batch will prompt the user to enter a value or text to be stored in the given variable. Here are some examples: SET hello=World SET /A three=1+2 SET /P menu=? Variable names can be any alphanumeric combination, including some symbols. However, you cannot use any of the following symbols: ! $ % ^ & * ( ) [ ] { } : ; " ' < > / \ ? You also cannot include spaces or use any of the reserved variable names listed in the next section. It is best to initialize all variables to a known value at the beginning of your script to prevent problems from arising. For example, if you have a user enter a number, but they leave the field blank or enter an invalid value - This can cause trouble in your program, but not if it is preset to a valid input prior to the user entering data! To use variables, place their name inside percentile signs, like so: %[Variable]% You can use variables in almost every command which takes input. Here are some common examples: COLOR %BG%%TX% ECHO %NAME% You can also use a variable as the name of a variable! The variable will be expanded into it's position in the statement when the block executes. Here are some examples: SET MAP%Y%=17 If the value of the variable "Y" was 5, then the variable "MAP5" is created with the contents "17" When doing some mathematical calculations, it can be convenient to know that the SET command can automatically perform basic arithmetic on variables. The format is as follows: SET /A [Variable][Operator]=(Number) For example, if I wanted to increase the value of the variable %TEST% by 5, I could use: SET /A TEST+=5 This also goes for the other three basic functions. SET can add, subtract, multiply, and divide in this way. This can be helpful for shortening commands, which when done in large amounts can slightly increase the execution speed of your script as well as also decreasing it's overall file size. It also saves time when typing! Part 1.3b Special Variables There are a few special variables whose uses are restricted because of the way Batch works. Their names and a very general description of what they do are listed below: %0 The name of the file being run %1 ... %9 The arguments passed to this file, separated by spaces after the file name %CD% The current directory of the file %HOMEDRIVE% The current drive letter, or the Windows drive letter %OS% Version of the Windows interpreter. This is typically "Windows_NT" and can be used to perform a brief OS check %TIME% This is the system time, formatted as HH:MM:SS.SS %DATE% This is the system date, formatted as DAY MM/DD/YYYY %TEMP% The directory of the system's temporary folder %ERRORLEVEL% This is automatically set on the completion of some commands %COPYCMD% This changes the behaviour of the COPY command slightly Part 1.4 Basic Window Controls Now that you know how to create a script, initialize it, and use variables, you probably want to know "How to I control the screen?" The screen, also called the "Console" or "Terminal" window, is typically about 100 columns wide by 40 columns tall by default. It's title is by default the directory of the Windows command interpreter. The screen colors are a drab combination of light gray text on a white background. Quite stagnant and boring, but luckily you can change all of this with a few simple commands! The first, easiest, but most often overlooked point to touch upon: The title bar. Most scripts leave this at it's default setting, but this looks boring and even bad at times. Using the "TITLE" command, you can change the text in the title bar. It's syntax is as follows: TITLE (Title text) You can use variables and almost all characters in the title bar of your script. Here are a few examples: TITLE Version %VER% TITLE My Game Next, the window's size. This affects how much text you can fit on the screen, and you can change it on the fly whenever you like. A common mode is 80x25 text characters, but how do you get this? Windows size is a function of the "MODE" command, which controls various ports and I/O... As well as the screen itself. To change the size of the window, it's syntax is as follows: MODE CON:COLS=[Columns] LINES=[Lines] So for example, to change the window to 80x25 or 132x44: MODE CON:COLS=80 LINES=25 MODE CON:COLS=132 LINES=44 Unfortunately, due to the limitations of the Batch script, there is no easy way to dynamically position the cursor on screen, but you can partially control it in a passive manner. This is done by using the "CLS" or "CLEAR" commands, which will clear the entire screen and return the cursor to it's home position at the top left of the screen. These commands take no operators, so they are fairly straight forward. Now for everybody's favorite: Text colors! Everybody loves colors, and there's an easy way to change the screen colors in a Batch script. Unfortunately, it changes the colors for the entire screen, but there are ways to get around this that we will discuss later. In the meantime, here's how to modify the background and foreground (text) colors for the entire window. Using the "COLOR" command, you can specify which of 16 colors you would like to change to. It takes two values, background and foreground. They are both hex values, and they can both be changed on the fly by variables. It's syntax is as follows: COLOR [Background color][Text color] Please note that both the background and text color cannot be the same, otherwise the command will fail to execute. Below is a list of all 16 available colors: 0 = Black 8 = Gray 1 = Blue 9 = Light Blue 2 = Green A = Light Green 3 = Aqua B = Light Aqua 4 = Red C = Light Red 5 = Purple D = Light Purple 6 = Yellow E = Light Yellow 7 = White F = Bright White In some cases, these colors can be different, such as in the Wine emulator for Linux distributions, or in Windows 10, which is more along the lines of this: 0 = Black 8 = Dark Gray 1 = Dark Blue 9 = Blue 2 = Dark Green A = Green 3 = Blue B = Light Blue 4 = Red C = Salmon 5 = Purple D = Light Purple 6 = Brown E = Beige 7 = Light Gray F = White Part 1.5 Basic Text Controls The most common text controls in Batch are CLS and ECHO. The CLS and CLEAR commands share the same function, which is to clear the entire screen of text and return the cursor to the uppermost left corner, usually to begin a new screen. The ECHO command will print characters to this screen in order from left to right, top to bottom. There are a few special cases for ECHO: ECHO This will display whether or not command echo is enabled ECHO. This will create a blank line ECHO: This will also create a blank line, but can sometimes be a tiny bit faster. ECHO ON This enables command echo ECHO OFF This disabled command echo When using ECHO, you can use most text characters normally except for the following: | ( & ) > ! < % ON OFF Some of these characters can be printed normally with the use of an escape character, which is usually the carat (^) or the colon (:). ECHO can also display variables as part of the message, including embedded variables as follows: ECHO Hello world ECHO Fruit: %YEILD% ECHO: Apples > Oranges ECHO Titanium ^< Iron ECHO !MAP%Y%! Please note that name-embedded variables will only work if you first enable delayed expansions during the initialization of your program. If you try to ECHO the contents of a variable that does not exist, either the text used to call that variable will be displayed or it will resort to reporting the command echo status instead. Part 1.6 Basic File Controls The most common file controls anyone will use are TYPE, COPY, DEL, and DIR. TYPE will display the contents of a file on screen as if it were text. Obviously, this does not work very well for other kinds of files, but it can be convenient for displaying short files which change often or for displaying log files. It's syntax is very easy and is as follows: TYPE [File location and filename, including extension] For example, to display the contents of a file named "LOG.TXT" stored in the Windows folder, the command would be as follows: TYPE C:\Windows\LOG.TXT The TYPE command also has one special trick up it's sleeve, which uses data redirection, which will be explained in greater detail later. The TYPE command can create screenshots of the current window! TYPE CON > [File location and filename, including extension] COPY will create a copy of any file in a new location, and, if desired, with a new filename and extension. It's syntax is as follows: COPY [Source file location and name, including extension] [Destination file location and name] For instance, to copy the file "Document.rtf" stored in the Windows folder to the root of the disk with the new name and extension "File.txt" the command issued would be as follows: COPY C:\Windows\Document.rtf C:\File.txt The COPY command has a few command switches which can change it's behaviour for some special cases. All valid switches are listed below with a short explanation of their function. /A ASCII text file /B Binary copy /V Verify copy /Y Silent mode. Do not print a message when copying When /A is placed AFTER the source file, the source file will be copied as if it were ASCII text. When it is placed AFTER the destination file, the destination will be created as if it were ASCII text. When /B is placed AFTER the source file, the source file will be copied exactly, as if it were a binary file. When it is placed AFTER the destination file, the resulting file will be created as if it were a binary file. Placing switches between the COPY command and it's source file will apply the switch to both the source and destination. The /V and /Y switches can only be placed between the COPY command and the source file. They will not work elsewhere. The COPY command can also copy text directly from the scren, just as TYPE can print a kind of screenshot, COPY can do the same. The syntax is as follows: COPY CON [File location and filename, including extension] COPY has one last trick up it's sleeve - It can also combine files while copying! The syntax to do this is actually simpler than you might think, and switches also still work as normal with this function as well. This specifies multiple files and one destination: COPY [File1]+[File2]+[File3] [Destination] There can be as many source files for this as you wish, so long as the command does not exceed 256 characters in length. One caveat to this technique is that the copy will fail if the first file does not exist, so it can be helpful to make the first file "NULL" or ensure it's existence so that the copy will always create a result. The next command has two variations: DEL and ERASE. Both commands do the same thing in the same way. Both commands when given a filename and location will delete the specified files. Wildcards (An asterisk in the case of Batch) can be used to automatically select several files with the same or similar names, and even to select all files in a directory. The typical syntax of DEL is as follows: DEL [File location and filename, including extension] You can also specify more than one file, as long as the command does not exceed 256 characters in length. DEL, like COPY, also includes a few command switches to change it's behaviour slightly. Each valid switch is listed below, along with a short explanation of it's use. /P This will prompt the user yes or no for each file /F Ignore read-only flags and delete all files regardless /S Delete files from subfolders as well /Q Quiet mode, do not give the user a message at all Files with excessively long paths or filenames cannot be deleted in this way. Some reserved filenames include: CON NUL COM1 COM2 COM3 COM4 LPT1 LPT2 LPT3 AUX PRN The final command, DIR, is less useful when doing general manipulation, but can sometimes be useful anyways. The DIR command is shorthand for directory, and as the name implies it will show the contents of the specified folder or the details of the specified file (the 'directory'). It's syntax is: DIR [File location and filename, including extension, or a folder name] For example, if you were to show the directory of the folder Documents, or the details of a file named "Calc.exe" in the Windows folder, the commands would appear as follows: DIR C:\Documents DIR C:\Windows\Calc.exe Like COPY and DEL, DIR also has command switches, but they are geared more towards the formatting of it's output instead. All valid switches are listed below. /P Pause between screens for directories that exceed the size of the current window /W Show less details but arrange filenames widthwise to save vertical space on the screen Part 1.7 Data redirection Data redirection! This allows the output of a command to be passed to another command or file, or vice versa, in the sense that the input for a command can be taken from the output of another. To do this, Batch uses a few symbols. Below are all of them and their meaning: > Direct output of command into a new file. Clear the file if it exists already and overwrite it with the new contents >> Direct output of command into an existing file. This will just create a new line in the specified file. < Direct command to take input from the specified file. This will type a file as input to a command | Pipe the output of a command into another || If the command to the left of the double pipe fails, then run the command to the right & Run the command on the left of the ampersand, then run the command to the right && If the command to the left of the double ampersand succeeds, then run the command to the right In Batch, there are several devices which can be redirected to as well. The names and functions of these devices are shown below: CON The console, as in the window where text is shown to the user NUL The "bit bucket" as some call it, everything goes in and nothing comes out. Redirecting information here will throw it away PRN This will direct the output to the default printer selected in Windows LPTn This will direct the output straight to the specified parallel port, when n is between 1 and 3 COMn This will direct the output straight to the specified serial port, when n is between 1 and 4 Part 1.8 Speed control