Learning never exhausts the mind

Published on by

To elevate the permissions for batch files manually, you would right-click on it and choose Run as Administrator. Here is a way to automatically elevate a batch file that requires elevated privileges to run correctly.

This is equivalent to choosing "Run as Administrator" by right-clicking a batch file. In either case, the UAC prompt would still show up.

Copy and Paste this snippet into the top of the batch file to automatically prompt for admin rights if it does not already have them.

:: BatchGotAdmin
:-------------------------------------
REM  --> Check for permissions
IF '%PROCESSOR_ARCHITECTURE%' EQU 'amd64' (
   >nul 2>&1 "%SYSTEMROOT%SysWOW64icacls.exe" "%SYSTEMROOT%SysWOW64config"
 ) ELSE (
   >nul 2>&1 "%SYSTEMROOT%system32icacls.exe" "%SYSTEMROOT%system32config"
)

REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
    echo Requesting administrative privileges...
    goto UACPrompt
) else ( goto gotAdmin )

:UACPrompt
    echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%getadmin.vbs"
    set params = %*:"=""
    echo UAC.ShellExecute "cmd.exe", "/c ""%~s0"" %params%", "", "runas", 1 >> "%temp%getadmin.vbs"

    "%temp%getadmin.vbs"
    del "%temp%getadmin.vbs"
    exit /B

:gotAdmin
    pushd "%CD%"
    CD /D "%~dp0"
:--------------------------------------  

Leave a Reply

Fields marked with * are mandatory.

We respect your privacy, and will not make your email public. Hashed email address may be checked against Gravatar service to retrieve avatars. This site uses Akismet to reduce spam. Learn how your comment data is processed.