Skip to content

Instantly share code, notes, and snippets.

@neremin
Last active January 28, 2021 16:32
Show Gist options
  • Save neremin/3a4020c172053d837ab37945d81986f6 to your computer and use it in GitHub Desktop.
Save neremin/3a4020c172053d837ab37945d81986f6 to your computer and use it in GitHub Desktop.
Template for windows cmd shell scripts (BAT, CMD) which need to auto-request user run as Administrator. Plus script for fixing "Run as Administrator" on batch files.
@ECHO off
net session >nul 2>&1
IF %ERRORLEVEL% NEQ 0 GOTO ELEVATE
@GOTO ADMINTASKS
:ELEVATE
ECHO Elevated privileges are temporarily required to run script
cd /d %~dp0
mshta "javascript: var shell = new ActiveXObject('Shell.Application'); shell.ShellExecute('%~nx0', '', '', 'runas', 1); close();"
EXIT /B
:ADMINTASKS
echo Fixing "Run as Administrator" shell menu for BATCH scripts
reg add "HKCR\batfile\shell\runas\command" /ve /f /t REG_SZ /d "%SystemRoot%\System32\cmd.exe /C \"\"%%1\"\" %*"
reg add "HKCR\cmdfile\shell\runas\command" /ve /f /t REG_SZ /d "%SystemRoot%\System32\cmd.exe /C \"\"%%1\"\" %*"
PAUSE
@ECHO on
@ECHO off
net session >nul 2>&1
IF %ERRORLEVEL% NEQ 0 GOTO ELEVATE
@GOTO ADMINTASKS
:ELEVATE
ECHO Elevated privileges are temporarily required to run script
cd /d %~dp0
mshta "javascript: var shell = new ActiveXObject('Shell.Application'); shell.ShellExecute('%~nx0', '', '', 'runas', 1); close();"
EXIT /B
:ADMINTASKS
: Set code page to UTF8 if your script encoding is (and contains non-ASCII chars)
chcp 65001
: Add your elevated commands here
PAUSE
@ECHO on
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment