3

I have a batch script:

test.bat

echo first arg is %1
pause

That I want to invoke from a vbscript with admin rights like so:

test.vbs

Set UAC = CreateObject("Shell.Application")
UAC.ShellExecute "test.bat", "argument", "", "runas", 1

This works ok but I am unable to pass a path argument that contains spaces as a single argument. Basically, I need to enclose the argument in spaces but whatever I try, it doesn't work. It looks like it invokes the batch, but the cmd window just flashes up and disappears so I don't know what is going wrong. I've tried:

UAC.ShellExecute "test.bat", """has spaces""", "", "runas", 1

and

UAC.ShellExecute "test.bat", Chr(34) & "has spaces" & Chr(34), "", "runas", 1

and

UAC.ShellExecute "test.bat", '"has spaces"', , "runas", 1

and

UAC.ShellExecute "cmd", "/c test.bat " & chr(34) & "has spaces" & chr(34), "", "runas", 1

But no luck. Any suggestions what I'm doing wrong?

Community
  • 1
  • 1
matt burns
  • 24,742
  • 13
  • 105
  • 107
  • Not sure *why* that doesn't work but this should; `UAC.ShellExecute "cmd", "/c test.bat " & chr(34) & "has spaces" & chr(34), "", "runas", 1` – Alex K. Nov 16 '12 at 10:43
  • 4
    Odd, its working for me if I pass the full path; /c c:\temp\test.bat – Alex K. Nov 16 '12 at 10:48
  • Ah yes, me too, thanks! Very odd though, will investigate more... – matt burns Nov 16 '12 at 10:50
  • passing cmd the args "/k test.bat " (/k keeps the window open) show me that it is running in \windows\system32 which is why the batch script was not found – matt burns Nov 16 '12 at 10:54
  • Ah makes sense perhaps runas causes it to ignore the current directory of the executing user – Alex K. Nov 16 '12 at 10:55
  • @AlexK. : https://gist.github.com/3f66e47a56368155f920 the chr(34) trick doesn't work for me – prongs Jan 12 '13 at 11:02

1 Answers1

4

The way to get this working is:

UAC.ShellExecute "cmd", "/c """"c:\test.bat"" ""has spaces""""", "", "runas", 1

The important thing to note when using runas to invoke admin user rights, is that the working directory will change to c:\windows\system32. Therefore, you need to specify the full path to the batch file so that it can be found.

I'm still not sure why this only works when passing the bat file as an argument to "cmd", rather than executing it directly.

All credit due to Alex K, from the comments.

In this case you need to quote the entire set of arguments to cmd, and each of the arguments also. You also need to double up the quotes. It looks a bit mad, but this is the best solution because otherwise it will fail if you have a space in any arguments and the bat file path.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
matt burns
  • 24,742
  • 13
  • 105
  • 107