Knowledge Base/Windows/Batch Scripting

From Thalesians
Jump to: navigation, search

Contents

Starting an executable in the background (without blocking)

Use

start c:\path\to\executable.exe

This will start executable.exe in a separate window without blocking your batch script. Thus if the above line is the last one in your batch script, executable.exe will be kicked off while your batch script terminates. This way you won't be left with a dangling command prompt window.

In fact, start is even more powerful than this:

START ["title"] [/Dpath] [/I] [/MIN] [/MAX] [/SEPARATE | /SHARED]
      [/LOW | /NORMAL | /HIGH | /REALTIME | /ABOVENORMAL | /BELOWNORMAL]
      [/WAIT] [/B] [command/program]
      [parameters]

    "title"     Title to display in  window title bar.
    path        Starting directory
    B           Start application without creating a new window. The
                application has ^C handling ignored. Unless the application
                enables ^C processing, ^Break is the only way to interrupt
                the application
    I           The new environment will be the original environment passed
                to the cmd.exe and not the current environment.
    MIN         Start window minimized
    MAX         Start window maximized
    SEPARATE    Start 16-bit Windows program in separate memory space
    SHARED      Start 16-bit Windows program in shared memory space
    LOW         Start application in the IDLE priority class
    NORMAL      Start application in the NORMAL priority class
    HIGH        Start application in the HIGH priority class
    REALTIME    Start application in the REALTIME priority class
    ABOVENORMAL Start application in the ABOVENORMAL priority class
    BELOWNORMAL Start application in the BELOWNORMAL priority class
    WAIT        Start application and wait for it to terminate
    command/program
                If it is an internal cmd command or a batch file then
                the command processor is run with the /K switch to cmd.exe.
                This means that the window will remain after the command
                has been run.

                If it is not an internal cmd command or batch file then
                it is a program and will run as either a windowed application
                or a console application.

    parameters  These are the parameters passed to the command/program

Nesting batch files

Batch files can be "nested". To call two.bat from one.bat, use the following command:

call two.bat

The execution of one.bat continues as soon as two.bat is done.

Passing on the command line arguments of the batch file to another batch file or executable

Within the batch file, the individual command line arguments are available as %1, %2, %3, ..., and the entire command line (omitting the batch file path and file name) is available as %*. For example, you can use the following batch file to test this (call it test.bat):

@echo off

echo First command line argument: [%1]
echo Second command line argument: [%2]
echo Third command line argument: [%3]
echo Fourth command line argument: [%4]
echo Fifth command line argument: [%4]
echo Entire command line: [%*]

The square brackets are for clarity. They are not essential.

You can call it as follows:

Test.bat foo "bar baz" 123

The output will be:

First command line argument: [foo]
Second command line argument: ["bar baz"]
Third command line argument: [123]
Fourth command line argument: []
Fifth command line argument: []
Entire command line: [foo "bar baz" 123]

Determining the batch file name

%~nx0 contains the name of the running batch file (without the path):

echo %~nx0

It may be a good idea to assign the value of %~nx0 to an environment variable with a more meaningful name which you can use later on:

set THIS_SCRIPT_FILE_BASENAME=%~nx0
echo %THIS_SCRIPT_FILE_BASENAME%

Determining the batch file directory

%~dp0 contains the name of the directory of the running batch file (without the name):

echo %~dp0

Save this as a batch file and try running it.

It may be a good idea to assign the value of %~dp0 to an environment variable with a more meaningful name which you can use later on:

set THIS_SCRIPT_DIRECTORY_PATHNAME=%~dp0
echo %THIS_SCRIPT_DIRECTORY_PATHNAME%

LEFT, RIGHT and MID equivalents for batch files

The following syntax can be used to obtain the results equivalent to those of BASIC's LEFT, RIGHT and MID:

set TEST=foobarbaz

echo Three leftmost characters ("LEFT")
set LEFT_TEST=%TEST:~0,3%
echo %LEFT_TEST%

echo Two rightmost characters ("RIGHT")
set RIGHT_TEST=%TEST:~-2%
echo %RIGHT_TEST%

echo Five characters starting from the fourth ("MID")
set MID_TEST1=%TEST:~3,5%
echo %MID_TEST1%

echo From the fourth character onwards ("MID")
set MID_TEST2=%TEST:~3%
echo %MID_TEST2%

echo Discarding the first one and the last two characters ("MID")
set MID_TEST3=%TEST:~1,-2%
echo %MID_TEST3%

Building a timestamp

The following code displays the current timestamp:

set hour=%time:~0,2%
if "%hour:~0,1%"==" " set hour=0%time:~1,1%
set timestamp=%date:~6,4%-%date:~3,2%-%date:~0,2%_%hour%-%time:~3,2%-%time:~6,2%
echo %timestamp%

Saving a variable value to a file

set value=foo
echo %value%>myfile.txt

Loading a variable value from a file

set /p value=<myfile.txt
echo %value%

echoing to STDERR

It is possible to echo to STDERR (rather than STDOUT):

echo Some error message >&2

Redirecting STDOUT and STDERR to a file

The following syntax can be used to redirect STDOUT alone to a file:

dir > output.txt

The STDOUT output of DIR will be redirected to output.txt. However, STDERR will not be redirected.

To redirect both STDOUT and STDERR, use the following syntax:

dir > output.txt 2>&1

Of course, the command doesn't have to be dir. It can be pretty much anything.

Determining the current user's home directory

Use %HOMEDRIVE% and %HOMEPATH%:

echo "%HOMEDRIVE%%HOMEPATH%"

Conditionals

if /I "%1" equ "debug" (
    set BUILD_CONFIG=Debug
) else if /I "%1" equ "release" (
    set BUILD_CONFIG=Release
) else (
    echo Please specify build config -- debug or release -- by running either
    echo.
    echo     run.bat debug
    echo.
    echo or
    echo.
    echo     run.bat release
    echo.
    exit 1
)

ECHOing blank lines

echo.

ECHOing pipe characters

echo This is a pipe character: ^|
Personal tools