Windows Batch Programming Notes and Examples

May 25, 2019

Recently I’ve been writing a lot of windows batch files that need to be compatible with both Windows 7 and Windows 10. I’ve decided to document some of what I have learned below.

Check if .bat file was ran with elevated privileges

WHOAMI /Groups | FIND "12288" >NUL
IF ERRORLEVEL 1 (
    ECHO This batch file requires elevated privileges
    EXIT /B 1
)

source: https://www.robvanderwoude.com/battech_elevation.php

Elevate Batch File on the Fly

If you want to automatically prompt for Administrative rights (using windows UAC), use the code below:

@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"
:--------------------------------------

source: https://sites.google.com/site/eneerge/scripts/batchgotadmin