Launch Batch Scripts as Administrator (with GUI UAC prompt)

Launch Batch Scripts as Administrator (with GUI UAC prompt)

posted May 28, 2011, 1:37 AM by Evan Greene   [ updated Dec 12, 2011, 3:58 PM ]
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>

This follows the original idea, except it attempts to use the cacls command instead of creating a folder in the system directory.  This is a little cleaner.  Also used proper code so it should work on non-english versions of Windows.

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.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章