I have a batch script:
echo first arg is %1
pause
That I want to invoke from a vbscript with admin rights like so:
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?
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.