Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Running a .bat file as administrator - Correcting current directory

0.00/5 (No votes)
20 Oct 2010 1  
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:
 
@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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here