Is it possible to embed and execute VBScript within a batch file without using a temporary file?

后端 未结 6 919
慢半拍i
慢半拍i 2020-11-22 04:39

People have been embedding and executing VBScript within batch files for a long time. But all the published solutions that I have seen (at the time this question was ori

6条回答
  •  一生所求
    2020-11-22 05:30

    And my attempt (first posted here).It resembles the jeb's solution ,but (at least according to me) the code is more readable:

    :sub echo(str) :end sub
    echo off
    '>nul 2>&1|| copy /Y %windir%\System32\doskey.exe ".\'.exe" >nul
    
    '& echo/ 
    '& cscript /nologo /E:vbscript %~f0 %*
    '& echo/
    '& echo BATCH: Translation is at best an ECHO.
    '& echo/
    '& pause
    '& rem del /q ".\'.exe"
    '& exit /b
    
    WScript.Echo "VBScript: Remorse is the ECHO of a lost virtue."
    WScript.Quit
    

    And the explanation:

    1. ' (single quote) is not forbidden symbol as a part of a file name in windows so there is no problem to have a file called '.exe
    2. There are few commands packed with windows that do nothing without command line parameters.The fastest (at doing nothing) and most light as a size (according to my tests) are subst.exe and doskey.exe
    3. So at the first line I'm coping the doskey.exe to '.exe (if it does not already exist) and then continue using it as '& (as the .exe extension should be in %PATHEXT%).This will be taken as a comment in VBScript and in batch will do nothing - just will continue with the next command on the line.

    There are some flaws of course .At least for the first run eventually you will need administrator permissions as the coping in %windir%\System32\ might be denied.For robustness you can also use '>nul 2>&1|| copy /Y %windir%\System32\doskey.exe .\'.exe >nul and then at the end: '& rem del /q .\'.exe

    With '.exe left in your path you could unintentially to use it in improper way , and the execution on every line of '.exe eventually could decrease the performance.

    ..And in the batch part commands must be only in one line.

    Update 9.10.13 (..following the above convention)

    Here's one more way which requires self-renaming of the batch file:

    @echo off
    goto :skip_xml_comment
    
    
    
       
          
       
    
    

    And a short explanation:

    1. When the batch is self-renamed and renamed again with the old name , and this is done in one line (or in brackets) the script will be executed with no errors.In this case is added also one call of CSCRIPT.EXE with .WSF file.Self-renaming is a little bit risky , but faster than a temp file.
    2. Windows script host does not care much for items outside of xml data as long as there are no special xml symbols & < > ; so @echo off and goto can be used without worries. But for safety it's good to put batch commands in xml comment (or CDATA ) section .To avoid error messages from the batch I've skipped the
      热议问题