Windows Batch Script - Getting Script Location (Directory/Path)

Last Modified: Thu, 28 Oct 2010 19:54:22 +0000 ; Created: Fri, 26 Sep 2008 23:12:00 +0000

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 located.

The second line causes the script to change to the directory where the script is located.

See Call command for further information.

Windows 7 Bug

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.

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%

Work Around

I've filed a bug with Microsoft at https://connect.microsoft.com/PowerShell/feedback/details/617705/windows-shell-bug-with-how-dp0-is-resolved.

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.