Current Directory / folder of a Batch file run As Administrator

It is a very lucky software developer that doesn’t have to interact with a microsoft windows batch file (.bat) ever now and again, recently my luck ran out and I came across a funny problem:


In windows 7, if your batch file does anything interesting (such a registering a COM dll) you may have to run it ‘As Administrator’. When you run it as administrator you may notice that a strange thing happens, it may be run with a different current/working folder to the folder in which it resides – whereas when run normally its current folder is its local folder.


This can be a real problem if the batch file needs to reference other files in its folder (such as the COM dll to be registered in my example above…)


Well not to worry, it turns out that to change batch file’s current directory to its local directory we just issue this rather esoteric command at the top of the file:


pushd %~dp0


The pushd bit I get, as for the rest….. well I am just glad it works!