Get the directory of a file in the Windows CLI

When you script batch files it is very important that you know in which path you are. Especially when you make relative file and folder operations.

C:Userssyss>echo %cd%
C:Userssyss

As you can see the current workingdirectory ist C:userssyss

When you make a relative file operation, let’s say to …anotheruser it is very important that you have not been forced in another directory e.g. C:windowssystem32.

If you try to to access your desired directory from the system32 folder you will get an error. (or maybe access a directory with the same name, but located at another place)

Most commonly you are forced in another directory when you start batch files from an UNC path. Some companies map “My Documents” to a server share which resolves into \serverusersusername

The thing is that these UNC paths are not supported, but only with a registrypatch. I think patching every client is way too much work and instead of this just put this header in every of your batch files

@echo off
setLocal EnableDelayedExpansion
set workingdir=%~dp0
set workingdir=!workingdir:~0,-1!
pushd !workingdir!

%~dp0 is an extended command, original it would be %0 which is the name of the batchfile. Adding ~dp inbetween resolves the path of the batchfile. Let’s say it would be \serveruserssyss

As you can see there is an trailing slash at the end of the path. In most cases it does not matter, but if you plan to make more folder operations like mounting a network drive it is important that you remove this very slash.

net use Y: \serveruserssyss will not work because Windows can’t interpret this as a valid networkshare nor directory. You might know that directories are special files. Obviously this very file (directory) is only found if you address it directly without slash.

This is a good way to remove the last X characters of a string.

set workingdir=!workingdir:~0,-1!

In fact the content of the variable will be altered and then saved into the variable again. This command goes from position 0 (index origin 0) to the last but one character (-1)

I will then change the directory with pushd and the network path. Pushd implicitly makes a net use to the UNC path (or normal path) with a Drive Letter from Z down to A. It skips a letter if it is already taken. If there is no driveletter available windows makes a strange output:

B:syss>pushd \serverUserssyss
" "
CMD does not support UNC paths as working directory. (free translation)

Do not forget to pop out of your directories:

popd

and you are done.