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:

@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:
For more information on cmd extensions:

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:

No comments:

Post a Comment