Click here to Skip to main content
15,867,686 members
Articles / Administrator
Tip/Trick

Running a .bat file as administrator - Correcting current directory

Rate me:
Please Sign up or sign in to vote.
5.00/5 (41 votes)
20 Oct 2010CPOL 143.2K   22   13
How to set the current directory correctly when running batch scripts as administrator
When you run a batch file as administrator under windows vista and 7 the current directory gets set to C:\windows\system32. This can prevent your scripts from working correctly if you use relative paths.
 
To fix this problem, include these two lines at the top of your .bat script:
 
VB
@setlocal enableextensions
@cd /d "%~dp0"
 
This will change the current directory to the location of the .bat file.
 
How it works:
 
@setlocal enableextensions - controls the visibility of environment variables[^] and enables cmd extensions[^].
 
@cd /d "%~dp0" - Changes the current directory to %~dp0 which is a special batch parameter[^] that expands to the drive and directory that batch file is located in.
 
%0 expands to the full path and file name of the batch file, adding the ~dp modifier in the middle to make %~dp0 reduces the %0 value to just the drive and path.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
United Kingdom United Kingdom
I discovered programming aged 11 with my school's BBC micro, and a book titled "Write your own space action games". (Their ideas of "space action" games were very different to mine. My ideas didn't include a bunch of * signs controlled via a text based menu)

I got hooked on VB for a while (mainly because I discovered I could replace the * signs with .bmp files) until someone pointed out the wonderful world of objects and Java. I also went thought a c++ phase.

I've now been a professional developer for 5 years.

My current language of choice is C#. I spend my free time playing with XNA and microcontrollers.

Comments and Discussions

 
GeneralReason for my vote of 5 Thank you so much! Pin
_WhiteRussian12-Nov-11 4:04
_WhiteRussian12-Nov-11 4:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.