Get the Batch Files Path in a Batch File

Date Published: 07 December 2010

Get the Batch Files Path in a Batch File

I’m a huge fan of build automation, and all of my dev projects include scripts to build, test, deploy, run etc.  Sometimes these use PowerShell and quite often they use MSBuild (or occasionally NAnt) but batch files remain a very simple and powerful way to take care of automation business.  Today I’m trying to wrap up my use of NServiceBus on a project that’s going live with some CQRS goodness, and I want a simple way to kick off the host process while I’m doing development so I don’t have to go to the trouble of running the thing from Visual Studio.  Anyway, to make a long story short, I needed to refer to the current path of the batch file within the batch file itself.  I found that if you use this “keyword” it works:

%~dp0

So if you create a batch file called ShowFolder.bat that looks like this:

echo %~dp0

and you run it from anywhere on your system, it will give you the path of the batch file.  This can be very handy if you need to know a particular path because an app you’re using doesn’t expect relative paths, and you want your code to work anywhere it’s checked out (e.g. on any dev’s workstation as well as on the build server).

Note that it has a trailing slash, in my experience, so if you want to append a relative path to it (e.g. /src/Foo/bin/Foo.exe) you don’t need your leading slash:

%~dp0src/Foo/bin/Foo.exe

Not terribly readable, but it works.

Steve Smith

About Ardalis

Software Architect

Steve is an experienced software architect and trainer, focusing on code quality and Domain-Driven Design with .NET.