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 dialog from the batch via javascript ensures the short simple code.
The script below auto elevates a user to Admin rights correctly, when Yes is chosen in the dialog, but the error dialog popups (outside of Cmd window) "Windows cannot find 'test.bat'". Can it be since the path-to-file includes spaces? How to fix the code or suppress this error popup?
@echo off
:: test admin rights
>nul 2>&1 net file
echo '%errorlevel%'
MSHTA "javascript: var shell = new ActiveXObject('shell.application'); shell.ShellExecute("%~nx0", '', '', 'runas', 1);close();"
:: test admin rights
>nul 2>&1 net file
echo '%errorlevel%'
if !errorlevel! equ 0 echo Hello >%temp%\tst.txt
exit /b
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