Back to List
You are viewing an unformatted version of this file.
# Administrative Scripts
Below is the skeleton for a batch file (`.bat`) that relaunches itself with administrative permissions if none given.
The script has generic Argument parsing but it's generally recommended that you replace the argument parser with your own.
IF EXIST "%ADMINFILE%" GOTO SETFILE
IF NOT EXIST "%ADMINFILE%" GOTO NOADMIN
IF EXIST "%TEMP%\__admtemp.vbs" DEL "%TEMP%\__admtemp.vbs"
IF "%RUNASADMIN%"=="TRUE" GOTO ERRADMIN
IF "%~1"=="" GOTO RUNCMD
SET ARGS=%ARGS% ""%~1""
ECHO CreateObject("Shell.Application").ShellExecute "cmd.exe","/C SET RUNASADMIN=TRUE && ""%~0"" %ARGS%",,"runas",1 1>"%TEMP%\__admtemp.vbs"
cscript //Nologo "%TEMP%\__admtemp.vbs"
ECHO The script was launched as administrator but failes to get administrative
ECHO permissions. This is an indication that the elevation never happened, usually
ECHO because The User Account Control is disabled and/or you are not using an
ECHO administrative account
REM ==== YOUR CODE HERE ===
This is an explanation of the script in detail.
First, a random file name in the Windows directory is generated.
`%RANDOM%` is a number from `0` to `32767`.
This step is repeated until a name is found that is not yet used.
If a name could be found, the script tries to create a file under that name.
If it's possible, we either have administrative rights or **very** messed up NTFS permissions.
In This case, we delete the random file, the eventually existing admin launcher and run the user code at `:USERCODE`
This label is executed if `:SETFILE` could not write to the test file.
First, the script checks if `RUNASADMIN` is set to `TRUE`.
If it is, it means that the file has already restarted once automatically to be elevated but it failed.
In that case it goes to `:ERRADMIN`.
All batch file arguments are enclosed in "double double quotes" because this is how quotes are escaped in the VB language.
This means `script.bat a "b c"` becomes `script.bat ""a"" ""b c""`.
This loop is not very reliable and should be replaced with an argument validator if the script takes arguments at all.
**DO NOT USE** if the arguments are from an untrusted source.
This is the code that actually elevates the batch file.
It writes a small temporary VBScript file that will set `RUNASADMIN=TRUE` and then launch the current script with arguments.
That temporary VBScript is then executed and the current batch file run is exited.
This is where the code is placed that must be run under an administrator account.