Running a .bat file as administrator changes default directory

When you run a .bat file as administrator ("Run as Administrator") under Windows Vista and 7 the current directory gets set to C:\windows\system32. This can be confusing as this is not the same behaviour as when not running as administrator and can cause problems with your scripts if you use relative paths.

To fix this problem, include these two lines at the top of your .bat file:

@SETLOCAL ENABLEEXTENSIONS
@cd /d "%~dp0"

 This will change the current directory to the location of the .bat file.

How it works:

1. @SETLOCAL ENABLEEXTENSIONS - controls the visibility of environment variables and enables cmd extensions.

For more information on SETLOCAL: http://ss64.com/nt/setlocal.html
For more information on cmd extensions: http://ss64.com/nt/cmd.html

2. %0 is the full path and file name of the batch file. %~dp0 Expands %0 to a drive letter and path.

For more information on batch parameters: http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/percent.mspx?mfr=true

No comments:

Post a Comment