Back to List

You are viewing an unformatted version of this file. To get the formatted version, you have to enable JavaScript.
# 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. ## Script @ECHO OFF SETLOCAL :SETFILE SET ADMINFILE=%WINDIR%\%RANDOM%.%RANDOM% IF EXIST "%ADMINFILE%" GOTO SETFILE ECHO.>"%ADMINFILE%" IF NOT EXIST "%ADMINFILE%" GOTO NOADMIN DEL "%ADMINFILE%" IF EXIST "%TEMP%\__admtemp.vbs" DEL "%TEMP%\__admtemp.vbs" ENDLOCAL GOTO USERCODE :NOADMIN IF "%RUNASADMIN%"=="TRUE" GOTO ERRADMIN SET ARGS= :ARGLOOP IF "%~1"=="" GOTO RUNCMD SET ARGS=%ARGS% ""%~1"" SHIFT GOTO ARGLOOP :RUNCMD ECHO CreateObject("Shell.Application").ShellExecute "cmd.exe","/C SET RUNASADMIN=TRUE && ""%~0"" %ARGS%",,"runas",1 1>"%TEMP%\__admtemp.vbs" cscript //Nologo "%TEMP%\__admtemp.vbs" ENDLOCAL GOTO :EOF :ERRADMIN 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 PAUSE GOTO :EOF :USERCODE REM ==== YOUR CODE HERE === ## Explanation This is an explanation of the script in detail. ### `:SETFILE` 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` ### `:NOADMIN` 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`. ### `:ARGLOOP` 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. ### `:RUNCMD` 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. ### `:USERCODE` This is where the code is placed that must be run under an administrator account.