Short answer is No unfortunately. The WScript Engine does not provide a way to pass script either piped or via the command arguments, the only option is using StdIn
to interpret and process the commands (expand on this below).
Using StdIn
to interpret and Execute Code Direct from the Command Line
Wasn't sure myself but wanted to test it out...
Worth noting that the testing below still requires a script to interpret the input which is probably not going to fit the requirement but is so generic I wouldn't class it as a temporary script.
The issue I can see is the more complex the code you want to pass in the harder it will be to pipe through to the cscript.exe
program.
Here is a simple example that just pipes a MsgBox()
call to cscript.exe
.
Command line:
echo MsgBox("test piping") | cscript.exe /nologo "test.vbs"
Contents of test.vbs
Dim stdin: Set stdin = WScript.StdIn
Dim line: line = stdin.ReadAll
Call ExecuteGlobal(line)
Handling Multiple Lines on the Command Line
Piping multiple lines from echo
isn't going to be easy it may work better if you use a character as a delimiter to break the commands up after being passed in. So for example;
echo MsgBox("test piping")^^^^Msgbox("test Complete") | cscript.exe /nologo "test.vbs"
then use
Split(stdin.ReadAll, "^")
to break up the command lines to execute.
Here is a more complex example;
Command Line:
echo Dim i: i = 1^^^^i = i + 2^^^^MsgBox("i = " ^^^& i) | cscript /nologo "test.vbs"
Contents of test.vbs
:
Dim line Dim stdin: Set stdin = WScript.StdIn
For Each line In Split(stdin.ReadAll, "^")
'Takes each line from StdIn and executes it.
Call ExecuteGlobal(line)
Next
Made a rod for my own back by using ^
as the delimiter as this has special meaning in the command line and needs to be escaped (which just so happens to be ^
), plus the fact it has to be escaped again when piped hence the ^^^^
.
Realised that breaking the lines down and executing them individually could cause more problems (for example a Function
definition would fail). This made me re-think the approach and found it should be even simpler.
Dim stdin: Set stdin = WScript.StdIn
Dim input: input = Replace(stdin.ReadAll, "^", vbCrLf)
Call ExecuteGlobal(input)