Last active
January 28, 2021 16:32
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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