batch-file

Topics related to batch-file:

Getting started with batch-file

From Microsoft Technet:

With batch files, which are also called batch programs or scripts, you can simplify routine or repetitive tasks. A batch file is an unformatted text file that contains one or more commands and has a .bat or .cmd file name extension. When you type the filename at the command prompt, Cmd.exe runs the commands sequentially as they appear in the file.

Batch File Names and Extensions

ExtensionRemarks
.batThis extension runs with MS-DOS and all versions of Windows
.cmdUsed for batch files in Windows NT family
.btmThe extension used by 4DOS and 4NT

To understand the difference between .cmd and .bat please see here.

Avoid names which are already the name of built-in commands. like tracert. There is a utility called tracert.exe. So, avoid naming a batch file tracert.bat

Running Batch File

The easiest way to run a batch file is simply double-clicking its icon. Or paste the file full path into a command prompt, or just its name if command Prompt was started from the batch file directory, then enter.

Example:

C:\Foo\Bar>test.bat
C:\Foo\Bar>C:\Foo\Bar\Baz\test.bat

Comments in Batch Files

Variables in Batch Files

For Loops in Batch Files

The for command accepts options when the /f flag is used. Here's a list of options that can be used:

  • delims=x Delimiter character(s) to separate tokens

  • skip=n Number of lines to skip at the beginning of file and text strings

  • eol=; Character at the start of each line to indicate a comment

  • tokens=n Numbered items to read from each line or string to process

  • usebackq Use another quoting style:

    Use double quotes for long file names in "files"

    Use single quotes for 'textStrings'

    Use back quotes for `command`

Echo

  • echo. will also display an empty string. However, this is slower than echo( as echo. will search for a file named "echo". Only if this file does not exist will the command work, but this check makes it slower.
  • echo: will behave just like echo(, unless message looks like a file path, e.g. echo:foo\..\test.bat. In this case, the interpreter will see echo:foo as a folder name, strip echo:foo\..\ (because it appears just to enter the directory echo:foo then leave it again) then execute test.bat, which is not the desired behaviour.

Directory Stack

  • Using pushd without parameters will print the stack.
  • The popd command will overwrite the current Current Directory value.

Elevated Privileges in Batch Files

Batch file command line arguments

If statements

There are a few syntax to choose from in an if statement. We will use if string1==string2 as an example.

1-Line Syntaxes

  • if string1==string2 commandA
  • if string1==string2 (commandA)
  • if string1==string2 (commandA) else (commandB)
  • if string1==string2 (commandA) else commandB
  • if string1==string2 (commandA)else (commandB)
  • if string1==string2 (commandA)else commandB

Multiline Syntaxes

if string1==string2 (
    commandA
)

Or

if string1==string2 (
    commandA
) else (
    commandB
)

There are still some extra syntaxes available.

Search strings in batch

Creating Files using Batch

If a file exists, > will overwrite the file and >> will append to the end of the file. If a file does not exist, both will create a new file.

Also, the echo command automatically adds a newline after your string.

So

echo 1 > num.txt
echo 1 > num.txt 
echo 2 >> num.txt 

will create the following file:

1
2

Not this:

1 1 2

or

1 2

Furthermore, you cannot just modify a single line in a text file. You have to read the whole file, modify it in your code and then write to the whole file again.

Changing Directories and Listing their Contents

Why is it important and what are they uses and advantages:

  • to open file or application in a directory using batch
  • to create andwrite and read files in a directory using batch
  • to know and list out all folders
  • to know where your batch file is running

Input and output redirection

  • You can add as many different redirections as you want, so long as the redirection symbol and file remain together and in the correct order.

Functions

You can add starting variables to the function by adding <parameter> to it's label. These starting variables can be accessed with %n where n is the starting variable's number (%1 for the first, %2 for the second. This %n method works for %1 - %9. For parameter 10 - 255, you will need to use the Shift command).
For example:

:function <var1> <var2>

Once you use call :function param1 param2, param1 can be accessed with %1, and param2 with %2.
Note: the <parameter> isn't strictly necessary, but it helps with readability.

A neat trick that is useful when many variable are flying about is to use setlocal and endlocal in tandem with %n. setlocal and endlocal essentially make the function it's own separate instance of the command prompt, variables set in it only stick around while it's in the frame.

If you are using setlocal and endlocal, and you are returning global values use this.

endlocal & set var=variable

This sets the global value var to variable. You can chain these together for multiple variables.

endlocal & set var=variable & set var2=variable number 2

This sets the global variable var to variable and the global value var2 to variable number 2.
Since code in code blocks are also performed simultaneously, you can do this as well.

if "%var%"=="" (
    endlocal
    set %~2=10
)

But, you cannot do this.

if "%var%"=="" (
    set %~2=10
    endlocal
)

Differences between Batch (Windows) and Terminal (Linux)

  • bitsadmin is deprecated in favor of the PowerShell cmdlet BITS but still works as of Windows 10 version 1607
  • certutil separates pairs of hexadecimal digits with a space, so md5sum will return an example value of d41d8cd98f00b204e9800998ecf8427e, while certutil displays the same value as d4 1d 8c d9 8f 00 b2 04 e9 80 09 98 ec f8 42 7e
  • To cd to another drive (for example, from C: to D:) the /d flag must be used
  • del can not delete folders, use rm instead
  • grep is so much more powerful than find and findstr, it's almost not fair to compare them; find has no regex capabilities and findstr has extremely limited regex capabilities ([a-z]{2} is not valid syntax, but [a-z][a-z] is)
  • for loops on the Windows command prompt can only use single-character variable names; this is the only time batch variable names are case-sensitive
  • for loops on the command prompt also use the variable form %A instead of %A% - forloops in batch scripts use the variable form %%A
  • md automatically creates any necessary parent directories, while mkdir needs the -p flag to do so
  • rem may not be used as an inline comment character unless it is preceded by a &
  • :: may not be used as an inline comment at all, and should also not be used inside of a code block (set of parentheses)
  • Note that some Windows command like ping still uses - as flags

Add delay to Batch file

Using Goto

So in other words, if the number the player inserted is 1, it'll go back to the :Name part of the code.

so if the input is equal to 1, go back to the line with :Name

Make Sure if you use this, the word begins with the Colen (:).

File Handling in batch files

Batch and VBS hybrids

Deprecated batch commands and their replacements

Batch and JSCript hybrids

Escaping special characters

Bugs in cmd.exe processor

In the example DEL File Extension, user X. Liu notices that this bug will not occurs when the file extension in the DEL command is less than 3 characters.

Bypass arithmetic limitations in batch files

Batch files and Powershell hybrids

Best Practices

Batch file macros

Random In Batch Files