Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

windows - How do you pass parameters containing spaces in vbs

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The way to get this working is:

UAC.ShellExecute "cmd", "/c """"c:est.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:windowssystem32. 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 so if this helped you, upvote his 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.6k users

...