Get path or location of currently executing batch/command file in Windows

I didn’t know it was this simple, and am posting this information on my blog so I find it in the future, but hopefully this will help someone else!

I’ve created a number of batch files over the years which routinely copy files from one location to another, usually as part of a backup strategy. However, I’ve always just hard-coded the paths of the drives, etc. into the batch files. While this works for drives which are permanently attached (or internal), it’s more fragile with external (flash/USB) drives. As I’ve never understood the logic of drive letter selection in Windows (letters usually are the same, but occasionally not), it meant that I was tweaking the drive letter in the batch file before running. Annoying, but it worked.

Thanks to more than a few web sites, I now know there is a much better way!

There are basically two decent options, depending on your scenario and requirements.

Option 1

If you are using drive letters (and not a mapped drive\network share), then you can use the variable %CD%.

It contains the “current directory.” So, that actually may be more than you wanted if the current directory isn’t the root of the drive.

image

Simple, just chop it off:

image

%CD:~0,2%

The colon and tilde character is a flag which indicates that a substring should be returned rather than the entire string. The first value is the zero-based starting index and the second is the number of characters you want to return:

image

The above starts at character 4, and includes 3 characters.

For fun, you can use negative values:

image

With only a single negative parameter, it returns the number of characters requested starting with the rightmost character.  (Check here for a bunch of examples on string manipulation.)

So, you could use knowledge in a batch file:

image

The above line uses robocopy (available in modern versions of Windows without an extra install) to copy from the folder \\server\Backups to the current path appended with \server\backups. So, if the batch file containing the robocopy command was executing on the J: drive, the resulting robocopy command would be:

image

By using the :~0,2 syntax, regardless of the folder the batch file is located in, it always copies to the root of the J drive (as the first two characters are J and : ).

Option 2

The other option is a bit different as it only works in a batch or command file.

image

Parameter zero (%0) in batch file represents the full path of the currently executing file (path and filename). The (dp) modifiers expand the value to be the “drive” and the “path,” excluding the file name.

image

You can manipulate the value as well:

image

I’m immediately going to adopt the first option into all of my “robocopy” batch files.