Scripts‎ > ‎

BatchGotAdmin

UPDATE 12/12/2011: Updated with some better code, thanks to Aaron Thoma
UPDATE 11/16/2011: I received some feedback from an international user who had issues using this script when special characters were included in the file name.  I've implemented some changes to fix these issues.

Finally got a batch script to prompt for administrator privileges in a GUI.

This will automatically elevate a .CMD or .BAT batch file using the standard UAC prompt.


Just put this at the top of your batch script.

BatchGotAdmin International-Fix Code:
@echo off

:: BatchGotAdmin
:-------------------------------------
REM  --> Check for permissions
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"

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"
    echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs"

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

:gotAdmin
    if exist "%temp%\getadmin.vbs" ( del "%temp%\getadmin.vbs" )
    pushd "%CD%"
    CD /D "%~dp0"
:--------------------------------------

<YOUR BATCH SCRIPT HERE>



BatchGotAdmin Original Code:
@echo off

:: Get ADMIN Privs
:-------------------------------------
mkdir "%windir%\BatchGotAdmin"
if '%errorlevel%' == '0' (
  rmdir "%windir%\BatchGotAdmin" & goto gotAdmin 
) else ( goto UACPrompt )

:UACPrompt
    echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
    echo UAC.ShellExecute %0, "", "", "runas", 1 >> "%temp%\getadmin.vbs"

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

:gotAdmin
    if exist "%temp%\getadmin.vbs" ( del "%temp%\getadmin.vbs" )
    pushd "%CD%"      
    CD /D "%~dp0"
:-------------------------------------
:: End Get ADMIN Privs

<YOUR BATCH SCRIPT HERE>

Basically this just creates a VBS Script on the fly and invokes the batch script using it.  It checks to see if the current window is running as administrator by attempting to create a folder that requires administrative access.  If the directory can not be created, then it invokes the UAC dialog, then closes the non-admin window.  The script can also be executed from an already open administrative CLI.
Comments