Windows Batch Script Location
Windows Batch Script - Getting Script Location (Directory/Path)
Inside a Windows batch file (.bat or .cmd) you can reference the drive and folder where the batch file is located by:
%~D0
CHDIR %~DP0
The first line causes the script to change to the drive where the script is run from. The second line causes the script to change to the directory where the script is located.
See Call command for further information.
Windows 7 has a bug in the handling of %~dp0 and %~f0 which can cause this to fail. When running a .cmd or .bat script and using %~f0 or %~dp0 to resolve the batch script name if the batch script name has spaces (ex: “my script.cmd”) and you chdir within the script then further references to %~dp0 will incorrectly resolve to the new cwd instead of the correct batch script location. This does not happen if the script name has no spaces in it.
Consider the example script below:
@REM When this script is named "test.cmd" (no spaces) it works as expected for the value of %~f0
@REM When this script is named "test with spaces.cmd" it does not work
echo "Stage 1: dp0 == %~dp0"
SET STAGE1=%~dp0
%~d0
cd "%~dp0"
mkdir TestSubFolder
cd TestSubFolder
echo "Stage 2: dp0 == %~dp0"
echo Should have gotten value %STAGE1%
I’ve filed a bug with Microsoft. In the mean time if you make the FIRST statements in your batch as follows you can still use this trick:
@REM Must set these first thing due to bug in Windows 7 when batch script filename has spaces in it
SET BATCH_SCRIPT_DRIVE=%~d0
SET BATCH_SCRIPT_FOLDER_PATHNAME=%~dp0
You could then do
%BATCH_SCRIPT_DRIVE%
CD "%BATCH_SCRIPT_FOLDER_PATHNAME%"
to make the current working drive and directory the same as your scripts.