At times, we need to run some batch files which require administrator privilege. In order to do this, we have to right click the file, then click run as admin. Errors will be shown if we run the batch file directly without elevated privilege. Is there a way to make the batch file elevate itself, if it doesn't have admin privilege?
There's a pretty good discussion on stackoverflow, with several solutions provided. Briefly, the basic flow is like this:
I think this answer is the most simple and neat, with the following reasons:
I made some modification to the original code, according to the other answers, final code and comment is posted here:
@ECHO OFF
:: the first line is to turn off output
:: check if we have admin privilege, do not output result, nor errors
NET SESSION 1>NUL 2>NUL
:: if not, jump to ELEVATE block
IF %ERRORLEVEL% NEQ 0 GOTO ELEVATE
:: jump to the batch script which needs admin privilege
GOTO ADMINTASKS
:: ELEVATE block
:ELEVATE
:: record current path
CD /d %~dp0
:: re-run this batch with admin privilege, using javascript
MSHTA "javascript: var shell = new ActiveXObject('shell.application'); shell.ShellExecute('%~nx0', '', '', 'runas', 1);close();"
:: exit
EXIT
:: our actual batch
:ADMINTASKS
:: add custom content below
we could remove comment to make it short:
@ECHO OFF
NET SESSION 1>NUL 2>NUL
IF %ERRORLEVEL% NEQ 0 GOTO ELEVATE
GOTO ADMINTASKS
:ELEVATE
CD /d %~dp0
MSHTA "javascript: var shell = new ActiveXObject('shell.application'); shell.ShellExecute('%~nx0', '', '', 'runas', 1);close();"
EXIT
:ADMINTASKS
let's add a test.cmd
to our desktop, with the following content:
@ECHO OFF
NET SESSION 1>NUL 2>NUL
IF %ERRORLEVEL% NEQ 0 GOTO ELEVATE
GOTO ADMINTASKS
:ELEVATE
CD /d %~dp0
MSHTA "javascript: var shell = new ActiveXObject('shell.application'); shell.ShellExecute('%~nx0', '', '', 'runas', 1);close();"
EXIT
:ADMINTASKS
net user
pause
Finally, we could forget to run our admin batch with right click, which needs a little modification