batch-file Elevated Privileges in Batch Files Requesting Elevated Privileges at Runtime


The following batch file will popup a UAC Prompt allowing you to accept elevated Administrator privileges for the batch session. Add your tasks code to :usercode section of the batch, so they run with elevated privileges.

@echo off
setlocal EnableDelayedExpansion
:: test and acquire admin rights
cd /d %~dp0 & echo/
if not "%1"=="UAC" (
    >nul 2>&1 net file && echo Got admin rights || (echo No admin rights & ^
MSHTA "javascript: var shell = new ActiveXObject('shell.application'); shell.ShellExecute("%~snx0", 'UAC', '', 'runas', 1);close();"))
:: re-test admin rights
echo/ & >nul 2>&1 net file && (echo Got admin rights & echo/) || (echo No admin rights. Exiting... & goto :end)

:: add your code here
echo Performing admin tasks
echo Hello >C:\test.txt

timeout /t 5 >nul
exit /b