Administrator's shortcut to batch file with double quoted parameters

XXB picture XXB · Mar 23, 2010 · Viewed 7.4k times · Source

Take an excruciatingly simple batch file:

echo hi
pause

Save that as test.bat. Now, make a shortcut to test.bat. The shortcut runs the batch file, which prints "hi" and then waits for a keypress as expected. Now, add some argument to the target of the shortcut. Now you have a shortcut to:

%path%\test.bat some args

The shortcut runs the batch file as before.

Now, run the shortcut as administrator. (This is on Windows 7 by the way.) You can use either right-click -> Run as Administrator, or go to the shortcut's properties and check the box in the advanced section. Tell UAC that it's okay and once again the shortcut runs the batch file as expected.

Now, change the arguments in the target of the shortcut to add double quotes:

%path%\test.bat "some args"

Now try the shortcut as administrator. It doesn't work this time! A command window pops up and and disappears too fast to see any error. I tried adding > test.log 2>&1 to the shortcut, but no log is created in this case.

Try running the same shortcut (with the double quotes) but not as Administrator. It runs the batch file fine. So, it seems the behavior is not because of the double quoted parameters, and it's not because it's run as Administrator. It's some weird combination of the two.

I also tried running the same command from an administrator's command window. This ran the batch file as expected without error. Running the shortcut from the command window spawned a new command window which flashed and went away. So apparently the issue is caused by a combination of administrator, the shortcut, and the double quotes.

I'm totally stumped, does anyone have any idea what's going on? I'd also like a workaround.

Answer

Luke picture Luke · Mar 23, 2010

I just ran Process Monitor on this and here is what I saw:

Run as User:

cmd /c ""C:\Users\Sunbelt\Desktop\test.bat" "some args""

Run as Admin:

"C:\Windows\System32\cmd.exe" /C "C:\Users\Sunbelt\Desktop\test.bat" "some args"

For some reason, the Run as Admin case is not quoting the entire command. It seems it is trying to run the command:

C:\Users\Sunbelt\Desktop\test.bat" "some args

I would guess that since the first space is quoted it actually trying to run the following command:

"C:\Users\Sunbelt\Desktop\test.bat some" args

And in Process Monitor logs there is a file system entry of "NO SUCH FILE" for "C:\Users\Sunbelt\Desktop\test.bat some". I don't know why it is different when run as Admin, but that's what appears to be happening.