Thursday, December 4, 2008

Hidden multiple argument BAT file execution with VBS


I have been writing a program that calls external programs using batch files in windows. Every time the call is made, the ugly command line box appears. After searching the net it seems that a simple way would be to use Visual Basic Script (VBS) to call the batch file in a special shell. Since the VBS interpreter is available on WinXP and above systems, I decided to try this vbs script that I found somewhere off the net.

Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & WScript.Arguments(0) & Chr(34), 0
Set WshShell = Nothing


Put the above code in a file called "invi.vbs" and then call the following from command line:

$>wscript.exe "invi.vbs" "mybatchfile.bat"


The batch file runs without a window! Thinking that this was great, I tried to run a batch file with arguments. Now that fails somehow because the interpreter seems to think that the entire WScript.Arguments(0) is a program name, i.e. "mybatchfile.bat arg1" will be treated as a program name instead of a batch file with a single argument.

Having not written VB since eons ago, I used my limited knowledge to concatenate the WScript.Arguments into a string. Somehow it just worked after replacing "invi.vbs" with my edits below.

Set WshShell = CreateObject("WScript.Shell")
dim toexec
For Each x in WScript.Arguments
   toexec = toexec & x & " "
Next
WshShell.Run toexec, 0, 1
Set WshShell = Nothing


Then, running it without quotes for the batch file, i.e.:

$>wscript.exe "invi.vbs" mybatchfile.bat arg1 arg2

No comments: