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

后端 未结 6 980
慢半拍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:29

    There is a very simple solution for this problem. Just use an Alternate Data Stream (ADS) to store the VBS code. To explain it simply, an ADS is another place where you can store other data in the same file, that is, a file is comprised of its original data plus any number of additional ADS's. Each ADS is identified separating its own name from the original file name via a colon. For example:

    test.bat                    <- a file called "test.bat"
    test.bat:script_.vbs        <- an ADS of file "test.bat" called "script_.vbs"
    

    You may find a more technicall and extensive description of ADS's in the web, but it is important to mention now that this feature works on NTFS disks only. Now, lets see how use this feature to solve this particular problem.

    First, create the original Batch file in the usual way. You may also start notepad.exe from the command line this way:

    notepad test.bat
    

    For my example, I inserted the following lines in test.bat:

    @echo off
    setlocal
    
    For /f "delims=" %%i in ('Cscript //nologo "test.bat:script_.vbs" "Select a folder"') do Set "folder=%%i"
    
    echo Result: "%folder%"
    

    Note the name of the VBS script. After test.bat was saved and Notepad closed, create the VBS script using Notepad, so enter this command at the command-line:

    notepad test.bat:script_.vbs
    

    And create the script in the usual way:

    Dim objFolder, objShell
    Set objShell = CreateObject("Shell.Application")
    Set objFolder = objShell.BrowseForFolder(0, "Select a folder.", &H4000, 0)
    If Not (objFolder Is Nothing) Then
       wscript.echo objFolder.Self.path
    Else
       wscript.echo 0
    End If
    

    Save this file and run test.bat. It works! ;)

    You may review the ADS's of test.bat file via the /R switch in dir command. You may read a more extensive explanation of this method and its limitations at this post.

提交回复
热议问题