can I run vbscript commands directly from the command line (i.e. without a vbs file)?

前端 未结 2 930
深忆病人
深忆病人 2021-01-24 23:33

In Python you are not obliged to use a file, you can specify -c \"...\" and gives the Python commands to the Python interpreter via a string on the command line.

2条回答
  •  有刺的猬
    2021-01-25 00:16

    No, the interpreters shipped with Windows (wscript.exe and cscript.exe) don't support that. If you can't create a file anywhere you're out of luck. You need some kind of wrapper script to transform the argument into something that VBScript interpreters can execute.

    The naïve approach would be to create a VBScript with an ExecuteGlobal statement like this:

    With WScript.Arguments.Named
      If .Exists("c") Then ExecuteGlobal .Item("c")
    End With
    

    However, that won't work correctly, because double quotes aren't preserved in the arguments. If you ran the above script like this:

    C:\> vbsrunner.vbs /c:"WScript.Echo "foo""

    it would effectively execute the statement WScript.Echo foo instead of WScript.Echo "foo", and I was unable to find a way to escape nested double quotes so that they're preserved in the argument.

    What will work is a batch script that writes the argument to a temporary file, and then executes that file with a VBScript interpreter:

    @echo off
    
    setlocal
    
    set "tempfile=%TEMP%\%RANDOM%.vbs"
    
    >"%tempfile%" echo.%~1
    cscript.exe //NoLogo "%tempfile%"
    del /q "%tempfile%"
    

    That way you can run VBScript statements on the command line like this:

    C:\> vbsrunner.cmd "WScript.Echo "foo" : WScript.Echo "bar""
    foo
    bar

    If you wanted to replicate Python's interactive mode you could use my vbsh, but that would still require the ability to create a file somewhere.

提交回复
热议问题