2

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!

Patrick R.
  • 412
  • 6
  • 15
  • `cscript /?` returns Usage: `CScript scriptname.extension [option...] [arguments...]`. Esoteric? Read [Run a VBScript / Windows Scripting Host (WSH) script](http://ss64.com/vb/cscript.html). – JosefZ Apr 02 '15 at 15:53
  • 3
    No this is a common feature of modern scripting languages, e.g. the CPython interpreter provides the -c "pass script as string" option. (For powershell see answer below). It is quite useful for environments were you want to control another interpreter but can not create files. – Patrick R. Apr 07 '15 at 12:36
  • It is very beneficial to pass a small script without having to access the file system first. For example, the Python interpreter supports it with `-c`. This works: `python -c "print 3+4"` – Marcel Taeumel Feb 21 '17 at 15:57

2 Answers2

2

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
Ekkehard.Horner
  • 38,498
  • 2
  • 45
  • 96
2

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
BuvinJ
  • 10,221
  • 5
  • 83
  • 96
  • This is the best answer and can be used to create a shortcut that runs an executable hidden: `cmd.exe /c echo CreateObject("Wscript.Shell").Run "notepad.exe", 0, false > run_hidden.vbs & start /wait wscript run_hidden.vbs & del run_hidden.vbs` – jmjohnson85 Mar 05 '19 at 22:42