Search code examples
batch-filevbscriptembed

Run VBScript code in a Batch file


Say I have a batch script and I would like to use VBScript to perform a certain task. It is a one liner in VBScript, and I would prefer to only have one file (which is the batch script) without any temporary files. Is this possible?

I know how to create a VBScript file from a batch script, run it and then delete it, but I don't want to do that because that involves creating an extra file.


Solution

  • Here are two ways - you can check for more here. The best way according to me (save whole code bellow as a .bat):

    <!-- :
    @echo off
    echo "Batch code here"
    cscript //nologo "%~f0?.wsf" %*
    exit /b
    -->
    <job><script language="VBScript">
      WScript.Echo "VBScript output called by batch"
      'Uncoment if you want to test the command line arguments
      'WScript.Echo (WScript.Arguments.Item(0))
    </script></job>
    

    You can also use mshta (mind that this the browser based vbscript and you have no access to the WScript object):

    @echo off
    setlocal
    :: Define simple batch "macros" to implement VBS within batch
    set "vbsBegin=mshta vbscript:Execute("createobject(""scripting.filesystemobject"")"
    set "vbsBegin=%vbsBegin%.GetStandardStream(1).write("
    set ^"vbsEnd=):close"^)"
    
    :: float numbers math
    %vbsBegin% 2.5+3.1 %vbsEnd% |more
    
    for /f %%a in ('%vbsBegin% 2.5+3.1 %vbsEnd%') do set result=%%a
    echo %result%