Reputation: 12005
To reproduce problem, create a simple batch file in a directory which has "&" in it.
e.g. in directory: "C:\temp\Jack & Dianne", Create run.bat:
@ECHO OFF
ECHO Hello
PAUSE
In Windows Explorer, right click and click "Run As Administrator". Batch file does not seem to run properly. i.e. : after I click Yes on Windows' "User Account Control" dialog, a command prompt window seems to flash up for an instant, then disappears.
If I rename the directory to remove the "&", then the batch file runs ok. I can reproduce the problem in Windows 10, but suspect it would be a general Windows issue.
Can anyone shed some light?
Upvotes: 3
Views: 1004
Reputation: 34260
The standard "open" command for .bat and .cmd files uses "%1" %*
as the template command. (This command is defined by the batfile and cmdfile progids under "HKLM\Software\Classes" in the relative subkey "shell\open\command".) This template command doesn't include the shell executable, just the target script ("%1"
) and parameters (*%
). Building the final command line that executes the %ComSpec%
shell is left up to the CreateProcess[AsUser]W
call, which also adds the proper quoting.
The way the "runas" verb is implemented requires an executable in the template command, so they explicitly set it to %SystemRoot%\System32\cmd.exe /C "%1" %*
. This forgets to quote the entire command line. Change it to the following:
`%SystemRoot%\System32\cmd.exe /C ""%1" %*"`.
To understand why the extra quoting is necessary, read the cmd /?
help for the /C
option. In summary, the /C
option keeps the quotes around the %1
script path only if the command line meets the following criteria: no /S
option and exactly two quotes that demarcate a string that contains one or more whitespace characters and no special characters (&<>()@^|
) and is the name of an executable file.
Because of the &
character in the path, CMD resorts to its regular behavior that strips the leading quote and the last quote. If nothing was dragged and dropped on the icon (i.e. no %*
), this will be the quotes around the %1
script path. With the whole command line quoted, CMD removes just the extra quotes instead of quotes that may be necessary in order to escape spaces and special characters in the script path or arguments.
Upvotes: 3