Run a Windows Batch File from the Current Directory

Here’s a little bit of Windows batch file magic that I never remember off the top of my head so I’ll log it here.

When you want your batch file commands to be executed from the current directory, putting the following at the start of your batch file should do the trick:
cd /d %~dp0

The “cd” meaning “change directory” is easy enough to understand. The “/d” tells cd to change drive and directory at the same time.

Now, that cryptic “%~dp0” is where the real work is done. %0 refers to the zeroth parameter of the batch file: the batch file itself. Adding the “~dp” modifier draws out the drive and path of the batch file sans its filename, hence the current directory.

To see more batch parameter modifiers, check out this page from Microsoft’s documentation.

Posted in Tech.