Search code examples
batch-filevbscriptwindows-installer

How to pass arguments to batch file from VBScript using ShellExecute


I am using VBScript first time for one of my task. Trying to build a Windows installer.

Before importing everything into Application Folder wanted to try it out externally but things are not working. I want to perform the installation with elevated permissions. Please correct my script.

Problem: If parameters sent to batch file contains spaces then the parameters are truncated.

My VBScript code:

' Get target folder path from "CustomActionData" property.
dim targetDirectory
targetDirectory =  "D:\New folder\batch files\"

' Prepare file path of install batch file.
batchFilePath = targetDirectory & "install-v2.bat"

' Pass targetDirectory as argument to batch file.
' Run the install batch file with elevated permissions as administrator
Set ObjShell = CreateObject("Shell.Application")
ObjShell.ShellExecute batchFilePath, targetDirectory, , "runas", 0

My Batch file:

@echo off

set HEADER=[MY-APP-NAME] %DATE% %TIME%
set TARGET_DIRECTORY=%1
set LOG_LOCATION="C:\Users\PureAjax\Downloads\batch-experiments\log.txt"

echo %HEADER% -- Instalation process started -- >> %LOG_LOCATION%
echo %HEADER% Target Directory %TARGET_DIRECTORY% >> %LOG_LOCATION%

rem will be using TARGET_DIRECTORY to achieve my task

echo %HEADER% -- Instalation process finished -- >> %LOG_LOCATION%
@pause

Log file

[MY-APP-NAME] 28-03-2020 23.07.15.78 -- Instalation process started -- 
[MY-APP-NAME] 28-03-2020 23.07.15.78 Target Directory D:\Newfolder\batchfiles\ 
[MY-APP-NAME] 28-03-2020 23.07.15.78 -- Instalation process finished -- 
[MY-APP-NAME] 28-03-2020 23.09.13.66 -- Instalation process started -- 
[MY-APP-NAME] 28-03-2020 23.09.13.66 Target Directory D:\New 
[MY-APP-NAME] 28-03-2020 23.09.13.66 -- Instalation process finished -- 

It can me seen in the log file that if path does not contain spaces then batch file receives the full path otherwise its truncated. Alternatively, Is there a way to pass arguments to batch file directly while building MSI installer?

Tried below solutions but they didn't work

  1. arguments = Chr(34) & targetDirectory & Chr(34) and the pass arguments to batch file

  2. ObjShell.ShellExecute "cmd", batchFilePath, arguments, "runas", 0


Solution

  • There seems to be a bug which prevents using double quotes in parameters. You can try

    ObjShell.ShellExecute "cmd",_ 
                          "/c """"" & batchFilePath & """ """ & targetDirectory & """""",,_
                          "runas", 0
    

    where %1 will be received with double quotes as "D:\New folder\batch files\".

    Alternatively, you can send the parameter with replaced spaces

    p = Replace(targetDirectory, " ", "_") 
    ObjShell.ShellExecute batchFilePath, p , , "runas", 0
    

    and then replace it back in batch file

    set TARGET_DIRECTORY=%1
    set TARGET_DIRECTORY=%TARGET_DIRECTORY:_= %