Floating Point Arithmetic | Working around the limitations of the command processor. |
SET /A | Basic Integer Arithmetic. |
Large Integers | Working around the limitations of the command processor. |
Percent | Basic Percent arithmetic. |
Ansi to Unicode | Ansi to Unicode. |
Command Grouping | Grouping Commands in blocks using Parentesis. |
Multiple Commands in Single Line | How to enter multiple commands into a single line. |
Conditional Execution | Conditional Execution Based on Result of Previous Command. |
File Line Count | Use FIND command to count file lines, store line count into a variable. |
Does String1 begin with String2? | Check if one string starts with another. |
Drive Types | List all drives connected and corresponding types, i.e. Fixed, CD-ROM, Removable. |
Echo a Blank Line | How to use ECHO to output a blank line. |
Escape Characters | Escaping special characters in DOS batch when delayed variable expansion is enabled or disabled. |
Exit | Exit on key pressed. |
Exit | Exit on key pressed with customized message. |
Exit Delayed | Delayed exit without user interaction. |
File Size in Bytes | Use FOR command to determine the file size in bytes. |
Initializing a batch | Commands that are typically executed at the beginning of a batch script. |
Open the Registry Editor at a given Key | Opening the Registry Editor at a defined Key. |
RunAs Administrator | Force a batch to run as different user via RunAs command. |
Multiple Lines for Single Command | How to continue a command in the next line. |
Unicode to Ansi | Convert a file to Ansi. |
Date Time for Unique String | Create a unique string using current date and time. |
Version History | Add a version history, track date, author and description of each change. |
Window Color | Change the Window Color. |
Window Size | Change the Window Size. |
Window Title | Change the Window Title. |
Check File for Zero Bytes | Use FOR command to show or delete empty files. |
Description: | Floating point arithmetic can be achieved by moving the fractions into the integer. I.e. A floating point equitation using values with 3 digits after the dot can be calculated as follows:
Floating Point: 12.055 + 1.001 = 13.056 Integer: 12055 + 1001 = 13056 |
||
Script: |
|
||
Script Output: |
|
Description: | The SET /A command can be used for basic arithmetic.
You can write SET /a y=3*x or SET /a y=3*%x%. Both are correct. The command interpreter is smart enough to recognize variables within a formula. |
||
Script: |
|
||
Script Output: |
|
Description: | An easy way to convert an ANSI encoded file to UNICODE is by running a TYPE
command in a new instance of CMD.exe with option /U and piping the output into a new file.
The following command converts a text file named myfile.txt into the UNICODE encoded file named myunicodefile.txt. Note that myfile.txt should be ANSI for this to work correctly. |
||
Script: |
|
Description: | Use parenthesis to group commands into a block. Command blocks are useful in combination with
e.g. IF or FOR commands.
An opening parenteses in a line will tell command processor that more lines will follow. |
||
Script: | Download: BatchCommandBlock.bat
|
||
Script Output: |
|
Description: | Use & to separate multiple commands within a single command line. | ||
Script: |
|
Description: | Command1 && SuccessCommand
Command1 || FailCommand Command1 && SuccessCommand || FailCommand The && operator can be used to execute a command only when the previews command succeeded. The || operator can be used to execute a command only when the previews command failed. Example 1 Show a message only when the string "ERROR" exist in the logfile.log file. The find command succeeds when the string "ERROR" exist in logfile.log. The output of the find command is redirected into the NUL devise since we don`t want to see any of its output in the output window. Example 2 Show a message only when the string "ERROR" doesn`t exist in the logfile.log file. The find command fails when the string "ERROR" doesn`t exist in logfile.log. The output of the find command is redirected into the NUL devise since we don`t want to see any of its output in the output window. Example 3 The Conditional Execution operators are useful with many DOS commands, i.e. the SET command. Note Be careful when combining the operators, i.e.: Command1 && (CommandBlock2) || (CommandBlock3)
To avoid this pitfall force CommandBlock2 to succeed, i.e. using a simple REM as last block command: Command1 && (CommandBlock2 & REM) || (CommandBlock3) or: Command1 && ( CommandBlock2 REM force success ) || ( CommandBlock3 ) |
||
Script: | Download: BatchConditionalExecution.bat
|
||
Script Output: |
|
Description: | Running the FIND command with option /v and empty search string will find all lines
Running the FIND command with option /c will output the line count only. The FOR command with option /f will parse the output, the line count in this case, and the set command put the line number into the cnt variable. |
||
Script: |
|
||
Script Output: |
|
Description: | Knowing a certain character combination that never occurs in string1 can help solving the exercise. Lets say @@@ never occurs in string1 then we can use it as prefix for string1 and reformulate the question to: Does string1 alter if we delete any occurrence of @@@+string2 within string1. If string1 alters then if string1 start string2 then string 1 will alter otherwise not. | ||
Script: |
|
Description: | The FSUTIL program can be used from the command line to query information about
the connected drives.
Return all currently connected drives: fsutil fsinfo drives Returns e.g.: Drives: C:\ D:\ E:\ F:\ Return the drive type for a given drive: fsutil fsinfo drivetype D:\ Returns e.g.: D:\ - Fixed Drive To get the drive type of all drives parse the output of fsutil fsinfo drives with a FOR command and run fsutil fsinfo drivetype |
||
Script: | Download: BatchDriveType.bat
|
||
Script Output: |
|
Description: | To ouptut an empty line using the ECHO command simply append a dot to the command. Otherwise the
ECHO command will show the current echo state. In fact it appears to be safe to always use the dot.
A problem has been identified: "echo." stops working when there is a file named "echo" in the current directory. Using "echo/" instead may be a better option. See this forum post for details. |
||
Script: |
|
||
Script Output: |
|
Description: | The command processor handles some characters in a special way and these characters won`t show up in the output as expected when using i.e. the ECHO command. The exclamation mark is handled differently if Delayed Expansion is enabled or disabled. | ||
Script: | Download: BatchEscape.bat
|
||
Script Output: |
|
Description: | GOTO:EOF command will end a DOS batch application no matter whether subsequent code follow. Adding a PAUSE command will allow the user to inspect screen outputs before the application window disappears. Forcing an empty line via ECHO will nicely separate the "Press any key to continue" message created by the PAUSE command from any previous output. | ||
Script: |
|
Description: | Letting the PAUSE command show the "Press any key to continue" message on exit may cause some confusion, since the application will finish and not continue. An ECHO command preceding the PAUSE command can be used to show a customize message. The text output of the PAUSE command can be omitted by piping its output into the NUL device. | ||
Script: |
|
Description: | As you develop DOS batch files you may find it annoying to have to hit a key when the application
finished just to close the window. You may want to have it close automatically but still being
able to briefly scan over the execution result shown in the window.
A way to create a delay in a DOS batch program is to ping the localhost or 127.0.0.1. Sending 2 pings (ping –n 2 ...) will cause a delay of very close to one second. Invoking multiple pings as needed gives control about the delay time. Showing the remaining delay time in the window TITLE will even let the user know what`s going on. I.e. replace the pause statement added earlier with the following code lines and run the application again. The menu will show a countdown of 5 seconds before closing the application. Changing the number 5 to 10 would result in a 10 second countdown. What it`s good for:
|
||
Script: |
|
Description: | Use the `z` specifier of FOR variable references to get the size of a file. | ||
Script: |
|
||
Script Output: |
|
Description: | At the beginning of a DOS batch file belongs the initialization of the command processor. This is to ensure subsequent DOS batch script will be handled by the command interpreter as we intended to. First let`s turn command-echoing off so that the output screen doesn`t get polluted with batch file content itself during execution. Second, in order to enable the great features of the command processor as required by most the other script code described here, the initialization code shall turn on Extensions and Delayed Expansion. | ||
Script: |
|
Description: | It`s known that opening the registry editor regedit.exe it will have the last registry key remembered and opens right where the it left off the last time it was running. The last registry key is being remembered in the registry itself using the LastKey value in HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Applets\Regedit. To have regedit.exe open up at a specific location we just have to set the LastKey value properly before invoking regedit.exe. This can be done with the REG command. | ||
Script: |
|
Description: | Force a batch to run as different user via RunAs command. This snippet checks the USERNAME environment variable. If it`s not `Administrator` then it automatically restart the batch with Administrator credentials using the RunAs command. Administrator password is required. | ||
Script: | Download: DosRunAsAdmin.bat
|
||
Script Output: |
|
Description: | Use ^ as the very last character in a line if you with to continue the command in the next line. | ||
Script: |
|
||
Script Output: |
|
Description: | An easy way to convert an UNICODE encoded file to ANSI is by running a TYPE
command in a new instance of CMD.exe with /A option and piping the output into a new file.
The following script converts a text file named myfile.txt into the ANSI encoded file named myansifile.txt. Note myfile.txt can be UNICODE or ANSI the result will always be an ANSI encoded file. |
||
Script: |
|
Description: | A string unique to the local host can be created out of the %date% and %time% system
environment variables.
For convenience the unique string created here will be a number in the format YYYYMMDDHHMMSSff whereas ff are the 1/100th fractions of a second. As long nobody modifies the system time and the command is not being called twice within a 1/100th of a second, each created UNIQUE string will be unique and in a sorting order. The example described here assumes that the %date% variable uses the format day MM/DD/YYYY and the %time% variable uses the format HH:MM:SS.ff. As the %time% variable may return only one digit for the hour before 10.00 AM and put a spacer to fill the missing 10th digit we will substitute the space characters in %time% with 0 by using %time: =0%. |
||
Script: |
|
||
Script Output: |
|
Description: | Having a version history within you DOS batch file is good practice in order to keep track of when changed what. Have the following code block close to the beginning of each batch file to present a nicely formatted version history. The version history can be updated by copying the last entry and modifying Date, Author, and Description appropriately. | ||
Script: |
|
Description: | The background and foreground color of a window can be changed using the COLOR command followed
by two hexadecimal digits:
1st - background 2nd - foreground The change will appear instantly for the whole window. The color codes are: 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 |
||
Script: |
|
Description: | To control the size of a window use the MODE command. The example shows how to size a window 90 characters horizontal and 10 lines vertical. | ||
Script: |
|
Description: | Application name and version of you application seem to make just the right title for the application window. Let`s store the title into a variable that way it can be reused later in the batch script in case we use the window title temporary to display something else. The TITLE command will set the window title. | ||
Script: |
|
Description: | Use the `z` specifier of FOR variable references to get the size of a file. Then show or delete the file if the size is zero. | ||
Script: |
|
||
Script Output: |
|