Windows Batch Programming Notes and Examples

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
    ECHO This batch file requires elevated privileges
    EXIT /B 1


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 )

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

    exit /B

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


1 comment to Windows Batch Programming Notes and Examples

  • JamesDoyle

    Steve…been a long time since we touched base…
    awesome stuff boss…i wrote a batch file to backup ADCS DB/Keys/Templates etc (for baremetal restores) and put them up on cloud storage on the hour every hour…to be swept up by VM Snaps on the hour, all run automagically by the Task Scheduler locally 🙂

    i would love to see more examples of what you are doing in this space…mbe we could trade some solutions 🙂

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.