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
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

One comment

  1. 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

Your email address will not be published. Required fields are marked *

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