Skip to main content

Batch File example to ensure the current user has elevated or administrator privileges to execute the specified commands.

@echo off
setlocal

:: Make sure the script is running as admin
call :ensure_admin

echo User has admin permissions
pause
exit 0

:die
    if not [%1] == [] echo %~1
    pause
    exit 1

:ensure_admin
    :: 'net session' is just a commmand that is present on all supported
    :: Windows versions, requires admin privileges and has no side effects, see:
    :: https://stackoverflow.com/questions/4051883/batch-script-how-to-check-for-admin-rights
    net session >nul 2>&1
    if errorlevel 1 (
        echo This batch script requires administrator privileges. Right-click on
        echo %~n0 and select "Run as administrator".
        call :die "Exiting."
    )
    goto :eof