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

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

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>