I want to derive a simple reliable method to auto elevate a running batch without using extra VBS files or elevated shortcuts, proposed in other threads. Calling the UAC dia
I fixed the script, and now it runs great. As per my research, this is the simplest reliable way to dynamically give a regular user Administrator privileges for the duration of that Cmd session in a running batch published anywhere.
It doesn't require using functions, hybrid batch & VBS constructs, extra files or elevated shortcuts. It is native to Windows. Users can add their own task code in the :usercode
section to run by the batch.
@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)
:usercode
:: add your code here
echo Performing admin tasks
echo Hello >C:\test.txt
:end
timeout /t 5 >nul
exit /b