user394592
user394592

Reputation:

Pass script to cscript/wscript as string

I'd like to know whether it is at all possible to pass a script as a string to cscript/wscript, similar to the -Command option of PowerShell. Alternatively, is there another way to execute VBS scripts from cmd?

The documentation of cscript/wscript does not list such an option, but as I'm not very familiar with Windows scripting, I am wondering whether I am missing something.

Thanks!

Upvotes: 2

Views: 2764

Answers (2)

BuvinJ
BuvinJ

Reputation: 11046

One way to do this is to write a vbs file from cmd via echo >, then execute it, then delete it.

Example:

echo WScript.Echo WScript.CreateObject("WScript.Shell").SpecialFolders(WScript.Arguments(0)) > test.vbs
cscript test.vbs "Desktop" //nologo
del test.vbs

Upvotes: 2

Ekkehard.Horner
Ekkehard.Horner

Reputation: 38745

Many (scripting) languages have a R(ead)-E(valuate)-P(rint)-L(oop) - Tool and/or process strings given on the command line. So using Powershell you can do:

powershell -command (2+3)*10
50

Perl:

perl -e "print 'hello';"
hello

For VBScript you have to roll your own; maybe starting starting here or here(ff).

A very simple (proof of concept) script that just deals with code from the command line:

Option Explicit

Dim goWAN : Set goWAN = WScript.Arguments.Named
Dim goWAU : Set goWAU = WScript.Arguments.UnNamed

If goWAN.Count <> 1 Or goWAU.Count <> 1 Or Not (goWAN.Exists("x") Or goWAN.Exists("e")) Then
   WScript.Echo "usage: ", WScript.ScriptName, "/x|/e ""code to execute/evaluate"" (use ' for "")"
Else
   Dim sCode : sCode = Replace(goWAU(0), "'", """")
   If goWAN.Exists("x") Then
      Execute sCode
   Else
      WScript.Echo Eval(sCode)
   End If
End If

output:

cscript 29416456.vbs
usage:  29416456.vbs /x|/e "code to execute/evaluate" (use ' for ")

cscript 29416456.vbs /e "(2+3)*10"
50

cscript 29416456.vbs /x "WScript.Echo 'Now: ' & Now"
Now: 4/3/2015 10:53:49 PM

Upvotes: 1

Related Questions