Hopefully "ScriptingTipsAndTricks" helps you with your batch file or vbscript scripting :-)
[Bottom][Contents][Prev]: RegularExpTestMm.hta (regular expression test tool)[Next]: Microsoft Tools
\->Useful Programs->My Tools (Tools written by me - Dennis Bareis)->VBS4CMD.VBS (used to imbed VBSCRIPT into a batch file)

VBS4CMD.VBS (used to imbed VBSCRIPT into a batch file)

This script is used to create batch files that can invoke VBSCRIPT code while not needing any external resources to be in place.

Some examples that use the output of this program:

  1. SetChar()
  2. SleepSeconds()
  3. Trim()
  4. WaitForTime()

The code performs all required escaping of difficult characters. It has been installed by the msi (but its not in the path). It is also listed below if you'd like to copy & paste it to recreate the vbscript.

Depending on your code you may want to create the VBS once and use many times or create each time.

SYNTAX: cscript.exe //NoLogo vbs4cmd.vbs /?

[]--------------------------------------------------------------------[]
| VBS4CMD.VBS Version 12.044 : Generates BATCH FILE CODE FROM VBSCRIPT |
|                  (C)opyright Dennis Bareis 2012. All rights reserved |
[]--------------------------------------------------------------------[]

This tool converts some VBSCRIPT which may have been purpose written to be
used in a batch file and converts this into a batch file subroutine which
can create and execute the code.

This allows you to develop & test the VBSCRIPT outside of the batch file and
only after its after fully tested do the reasonably painful conversion mostly
automatically.

The main reason you'd want to do this is is to generate a self contained batch
file rather than have with separate prerequisites.

The code is generated to SYSOUT for YOUR redirection and assumes the VBSCRIPT
will return a result so it executes the VBSCRIPT then the expected generated
BATCH FILE CODE b efore deleting all files, just delete or tweak as required :-)

The VBSCRIPT if it returns results will return these as batch "SET" commands.
Please see the MAKEMSI manual for more information.

CORRECT SYNTAX
~~~~~~~~~~~~~~
cscript.exe //NoLogo VBS4CMD.VBS NameOfVbsFile [NumbParmsVbsTakes] [> OutFile]

DETAILS
~~~~~~~

ERROR
~~~~~
Could not find the VBS file "/?"

@rem ERROR:Could not find the VBS file "/?"

The code for "VBS4CMD.VBS" (copy & paste if you wish)

'----------------------------------------------------------------------------
'    MODULE NAME:   Vbs4Cmd.VBS
'
'        $Author:   USER "Dennis"  $
'      $Revision:   1.0  $
'          $Date:   11 Jul 2014 19:31:06  $
'       $Logfile:   C:/DBAREIS/Projects.PVCS/Win32/ScriptingTipsAndTricks/Vbs4Cmd.vbs.pvcs  $
'----------------------------------------------------------------------------


'--- Init -------------------------------------------------------------------
const PgmVersion             = "12.044"
const ForReading             = 1
const OutputCmd              = "CMD"
const OutputVBS              = "VBS"
const Indent                 = "    "
const ENABLEDELAYEDEXPANSION = true
dim ErrTxt : ErrTxt = ""
dim Output : Output = OutputCmd
if  ucase(mid(wscript.FullName, len(wscript.Path) + 2, 1)) = "W" Then
    GenerateErrorMsgText "You can't use WSCRIPT on this VB script, use CSCRIPT instead!"
    wscript.echo         ErrTxt
    wscript.quit 999
end if
set oFS = CreateObject("Scripting.FileSystemObject")
if  wscript.arguments.count = 0 then
    DisplayHelpAndQuit "Need at least one parameter (name of VBS)"
else
    '--- Have at least one argument -----------------------------------------
    if wscript.arguments.count > 2 then
        DisplayHelpAndQuit "Too many arguments (takes ONE or TWO)!"
    end if
    Vbs2ConvertFile = wscript.arguments(0)   'Want to generate this VBS via BATCH file (want standalone batch file with no pre-reqs)
    NumberOfParms   = 0                      'How many parameters does the VBS you are converting take?
    if wscript.arguments.count = 2 then
       NumberOfParms = wscript.arguments(1)
       if ucase(NumberOfParms) = "VBS" or ucase(NumberOfParms) = ".VBS" then
          '--- VBS ----------------------------------------------------------
          Output        = OutputVBS
          NumberOfParms = 0
       else
           '--- CMD ---------------------------------------------------------
           if NumberOfParms > 9 then
              DisplayHelpAndQuit "The # of parameters to the VBSCRIPT must be from 0-9, make smaller value, fudge it and edit output if required!"
           end if
       end if
    end if
end if
if not oFS.FileExists(Vbs2ConvertFile) then
    DisplayHelpAndQuit "Could not find the VBS file """ & Vbs2ConvertFile & """"
end if

'--- Work out the name of the batch subroutine we are creating (from filename) ---
NameOfSubroutine = oFS.GetBaseName(Vbs2ConvertFile)

'--- How many parameters to pass? -------------------------------------------
if NumberOfParms <= 0 then
   VbsParms = ""
else
   '--- Assume the subroutine will take and pass this many parameters -------
   for x = 1 to NumberOfParms
       if x > 1  then VbsParms = VbsParms & " "
       VbsParms = VbsParms & """%~" & x & """"
   next
   VbsParms = " " & VbsParms
end if

'--- Mainline of Batch Subroutine -------------------------------------------
if Output = OutputCmd then
    '--- CMD ----------------------------------------------------------------
    GenerateOutputLineToStdout "@rem ++++++++++++++++++++++++++++++++++++++"
    GenerateOutputLineToStdout ":" & NameOfSubroutine
    GenerateOutputLineToStdout "@rem ++++++++++++++++++++++++++++++++++++++ Generated from """ & Vbs2ConvertFile & """"
    GenerateOutputLineToStdout Indent & "set VbsFile=%TEMP%\" & NameOfSubroutine & "-%random%.vbs"
    GenerateOutputLineToStdout Indent & "set CmdFile=%TEMP%\" & NameOfSubroutine & "-%random%.cmd"
    GenerateOutputLineToStdout ""
    GenerateOutputLineToStdout Indent & "call :MAKEIT_" & NameOfSubroutine
    GenerateOutputLineToStdout ""
    GenerateOutputLineToStdout Indent & "cscript.exe //NoLogo ""%VbsFile%""" & VbsParms & "  > ""%CmdFile%"""
    GenerateOutputLineToStdout Indent & "call ""%CmdFile%"""
    GenerateOutputLineToStdout ""
    GenerateOutputLineToStdout Indent & "del ""%VbsFile%"" >nul 2>&1"
    GenerateOutputLineToStdout Indent & "del ""%CmdFile%"" >nul 2>&1"
    GenerateOutputLineToStdout Indent & "goto :EOF"
    GenerateOutputLineToStdout ""

    '--- Generate the VBSCRIPT --------------------------------------------------
    GenerateOutputLineToStdout "@rem ++++++++++++++++++++++++++++++++++++++"
    GenerateOutputLineToStdout ":MAKEIT_" & NameOfSubroutine
    GenerateOutputLineToStdout "@rem ++++++++++++++++++++++++++++++++++++++"
end if
if Output = OutputVbs then
   GenerateOutputLineToStdout "dim Vbs : Vbs = """""
end if

'--- Generate the VBSCRIPT --------------------------------------------------
set ReadStream = oFS.OpenTextFile(Vbs2ConvertFile, ForReading)
LineCnt = 0
do  while ReadStream.AtEndOfStream <> true
    '--- Keep leading whitespace for readability & want to be able to "round trip" the code ---
    if Output = OutputCmd then
       GenerateVbsAsCmd rtrim(ReadStream.ReadLine)
    else
       GenerateVbsAsVbs rtrim(ReadStream.ReadLine)
    end if
loop
ReadStream.close
if Output = OutputCmd then
    '--- CMD ----------------------------------------------------------------
    GenerateOutputLineToStdout Indent & "goto :EOF"
end if
set oFS = Nothing
wscript.quit 0

'============================================================================
sub GenerateVbsAsVbs(ByVal VbScript)
'============================================================================
    VbScript = replace(VbScript, """", """""")   'Replace 1 quote with 2
    if  trim(VbScript) = "" then
        VbScript = "vbCRLF"
    else
        VbScript = """" & VbScript & """ & vbCRLF"
    end if

    GenerateOutputLineToStdout "Vbs = Vbs & " & VbScript
end sub


'============================================================================
sub GenerateVbsAsCmd(ByVal VbScript)
'============================================================================
    '--- Need to escape some specific characters (for .CMD) -----------------
    VbScript = replace(VbScript, "^", "^^")             'Need to double check this works, logic says its required...
    VbScript = replace(VbScript, "|", "^|")
    VbScript = replace(VbScript, "&", "^&")
    VbScript = replace(VbScript, ">", "^>")
    VbScript = replace(VbScript, "<", "^<")
    VbScript = replace(VbScript, "%", "%%")
    if  ENABLEDELAYEDEXPANSION then
        VbScript = replace(VbScript, "!", "!!")
    end if

    '--- Output this line ---------------------------------------------------
    if VbScript = "" then
       VbScript = "."               'Want echo.
    else
       VbScript = " " & VbScript
    end if
    LineCnt = LineCnt + 1
    if  LineCnt = 1 then
        Redirection = "  > "
    else
        Redirection = "  >> "
    end if
    GenerateOutputLineToStdout Indent & "echo" & VbScript & Redirection & """%VbsFile%"""
end sub


'============================================================================
sub GenerateOutputLineToStdout(ByVal CmdBatchLine)
'============================================================================
    wscript.echo  CmdBatchLine
end sub

'============================================================================
sub STDERR(ByVal HelpText)
'============================================================================
    ErrTxt = ErrTxt & HelpText & vbCRLF
end sub

'============================================================================
sub GenerateErrorMsgText(OptErrorMsg)
'============================================================================
    ErrTxt = ""
    STDERR "[]--------------------------------------------------------------------[]"
    STDERR "| VBS4CMD.VBS Version "& PgmVersion & " : Generates BATCH FILE CODE FROM VBSCRIPT |"
    STDERR "|                  (C)opyright Dennis Bareis 2012. All rights reserved |"
    STDERR "[]--------------------------------------------------------------------[]"
    STDERR ""
    STDERR "This tool converts some VBSCRIPT which may have been purpose written to be"
    STDERR "used in a batch file and converts this into a batch file subroutine which"
    STDERR "can create and execute the code."
    STDERR ""
    STDERR "This allows you to develop & test the VBSCRIPT outside of the batch file and"
    STDERR "only after its after fully tested do the reasonably painful conversion mostly"
    STDERR "automatically."
    STDERR ""
    STDERR "The main reason you'd want to do this is is to generate a self contained batch"
    STDERR "file rather than have with separate prerequisites."
    STDERR ""
    STDERR "The code is generated to SYSOUT for YOUR redirection and assumes the VBSCRIPT"
    STDERR "will return a result so it executes the VBSCRIPT then the expected generated"
    STDERR "BATCH FILE CODE b efore deleting all files, just delete or tweak as required :-)"
    STDERR ""
    STDERR "The VBSCRIPT if it returns results will return these as batch ""SET"" commands."
    STDERR "Please see the MAKEMSI manual for more information."
    STDERR ""
    STDERR "CORRECT SYNTAX"
    STDERR "~~~~~~~~~~~~~~"
    STDERR "cscript.exe //NoLogo VBS4CMD.VBS NameOfVbsFile [NumbParmsVbsTakes] [> OutFile]"
    STDERR ""
    STDERR "DETAILS"
    STDERR "~~~~~~~"

    '--- Display Error message ----------------------------------------------
    if OptErrorMsg <> "" then
        STDERR ""
        STDERR "ERROR"
        STDERR "~~~~~"
        STDERR OptErrorMsg
    end if
end sub

'============================================================================
sub DisplayHelpAndQuit(OptErrorMsg)
'============================================================================
    '--- Display help -------------------------------------------------------
    GenerateErrorMsgText(OptErrorMsg)
    wscript.stderr.writeline                  ErrTxt
    GenerateOutputLineToStdout     "@rem ERROR:" & OptErrorMsg
    wscript.quit 777
end sub


Microsoft awarded me an MVP (Most Valuable Professional award) in 2004, 2005, 2006, 2007, 2008 & 2009 for the Windows SDK (Windows Installer) area.Please email me any feedback, additional information or corrections.
See this page online (look for updates)

[Top][Contents][Prev]: RegularExpTestMm.hta (regular expression test tool)[Next]: Microsoft Tools


ScriptingTipsAndTricks© is (C)opyright Dennis Bareis 2003-2008 (All rights reserved).
Sunday September 07 2014 at 12:50pm
Visit ScriptingTipsAndTricks's Home Page
Microsoft awarded me an MVP (Most Valuable Professional award) in 2004, 2005, 2006, 2007, 2008 & 2009 for the Windows SDK (Windows Installer) area.