Any Windows batch script can be run from any folder by specifying a relative path to the script on the command line.  This ability is convenient when a script in a different folder needs to be run.  Instead of switching to the folder, running the script and then switching back, the relative path can be used to run the script, as in the following example:

Three commands using cd

> cd ..

> script.bat

> cd –

One command using a relative path

> ..\script.bat

Using just one command is quicker for scripts that are run frequently, however the script might behave differently if it relies somehow on the current directory.  For scripts that rely on a specific current directory, it is usually possible to write the script so that it automatically changes to that directory when it’s run.  This can be done by hard-coding the directory in the script, or by detecting which directory the script is in.  The second method is more generally useful because it can be re-used (copied) from other scripts without any modification.  The following example demonstrates one way this can be done:


@echo off



set START_DIR=%cd%

set SCRIPT_DIR=%~dp0






This script fills out two environment variables when it starts: START_DIR and SCRIPT_DIR.  START_DIR contains the directory where the user started the script from, and SCRIPT_DIR contains the directory where the script is located.  Windows batch scripts have pre-defined variables for both of these.  In this script, setlocal is used so the variables don’t end up in the global environment.