Batch File that Self-Elevates - but how?

Helios210

Honorable
Oct 26, 2013
1
0
10,510
Though I have scripts automating many things on my system I'm still reasonably new to batch programming, I'd also like to learn .vbs scripting but have no idea where to start. Currently I use an 'elevate' and 'elevate64' executable to elevate batch files that require administrative access, but then I found the following from 'eneege':

:: Ensure ADMIN Privileges

:: adaptation of <a href="https://sites.google.com/site/eneerge/home/BatchGotAdmin" rel="nofollow" target="_blank">https://sites.google.com/site/eneerge/home/BatchGotAdmi...</a> and <a href="http://stackoverflow.com/q/4054937" rel="nofollow" target="_blank">http://stackoverflow.com/q/4054937</a>

@echo off

:: Check for ADMIN Privileges

>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"

if '%errorlevel%' NEQ '0' (

REM Get ADMIN Privileges

echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"

echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs"

"%temp%\getadmin.vbs"

del "%temp%\getadmin.vbs"

exit /B

) else (

REM Got ADMIN Privileges

pushd "%cd%"

cd /d "%~dp0"

@echo on

)

Though it works, and I understand how it establishes whether it already has admin privileges, I don't understand how it actually self-elevates (I find the syntax rather obscure!). Would someone be able to explain this to me?

Much appreciated.

Helios 210.
 

corcorand82

Honorable
Nov 22, 2013
356
0
10,810
@echo off Prevents status report

:: Check for ADMIN Privileges :: acts as a comment statement, similar to <--comment-->

>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system" Opens Configuration files

if '%errorlevel%' NEQ '0' ( IF statement acts as filter

REM Get ADMIN Privileges REM means remark
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs" Create the pop up window in the %temp% folder

echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs" Run the getadmin shell

"%temp%\getadmin.vbs" Set a directory

del "%temp%\getadmin.vbs" Delete the file

exit /B exit the session

) else ( otherwise

REM Got ADMIN Privileges remark

pushd "%cd%" change directory/folder

cd /d "%~dp0" change directory to the current

@echo on give echo

) end statement