Characters like space, ampersand, pipeline etc. have a special meaning in Windows command line and should be escaped. Right-click Run as administrator action could be defined for a particular executable file type (extension in PATHEXT
variable) in corresponding registry keys - such as in HKEY_CLASSES_ROOT\cmdfile
and HKEY_CLASSES_ROOT\batfile
for Windows cmd
scripts:
assoc .cmd & assoc .bat
.cmd=cmdfile
.bat=batfile
Right-click Run as administrator actions for these file types are originally defined as follows:
reg query "HKEY_CLASSES_ROOT\cmdfile\Shell\runas\command"
reg query "HKEY_CLASSES_ROOT\batfile\Shell\runas\command"
HKEY_CLASSES_ROOT\cmdfile\Shell\runas\command
(Default) REG_EXPAND_SZ %SystemRoot%\System32\cmd.exe /C "%1" %*
HKEY_CLASSES_ROOT\batfile\Shell\runas\command
(Default) REG_EXPAND_SZ %SystemRoot%\System32\cmd.exe /C "%1" %*
Unfortunately, the double quotes are stripped out (see cmd /?
):
If /C
or /K
is specified, then the remainder of the command line
after the switch is processed as a command line, where the following
logic is used to process quote ("
) characters:
…
old behavior
is to see if the first character is a quote character and if so, strip
the leading character and remove the last quote character on the
command line, preserving any text after the last quote character.
Hence, we need to invoke the following command instead:
%SystemRoot%\System32\cmd.exe /C ""%1" %*"
rem ↑ ↑
To do that, open an elevated command prompt and run the following commands (run the reg add
command for batfile
as well, mutatis mutandis):
set auxvar=^%SystemRoot^%\System32\cmd.exe
reg add "HKEY_CLASSES_ROOT\cmdfile\Shell\runas\command" /ve /t REG_EXPAND_SZ /d "%auxvar% /C \"\"%1\" %*\"" /f
The operation completed successfully.
reg query "HKEY_CLASSES_ROOT\cmdfile\Shell\runas\command"
HKEY_CLASSES_ROOT\cmdfile\Shell\runas\command
(Default) REG_EXPAND_SZ %SystemRoot%\System32\cmd.exe /C ""%1" %*"
If you prefer doing that from a .bat
or .cmd
script, then the reg add
command should read as follows:
reg add "HKEY_CLASSES_ROOT\cmdfile\Shell\runas\command" /ve /t REG_EXPAND_SZ /d "%%SystemRoot%%\System32\cmd.exe /C \"\"%%1\" %%*\"" /f