Friday, 1 May 2015

SQL Server - run .bat file as Administrator



Description: To overcome the issue of .bat files not a executing the commands in administrator mode, either manually or through Task Scheduler.

When you run a batch file as Administrator under windows server, 8 or 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 as shown in the below image.


@setlocal enableextensions

@cd /d "%~dp0"


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

Explanation:

@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. This avoids .bat from crashing.

"%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.

No comments:

Post a Comment