如何使用 ShellExecute 从 VBScript 将参数传递给批处理文件

How to pass arguments to batch file from VBScript using ShellExecute

我第一次使用 VBScript 完成我的一项任务。正在尝试构建 Windows 安装程序。

在将所有内容导入应用程序文件夹之前,想在外部尝试一下,但没有任何效果。我想以提升的权限执行安装。请更正我的脚本。

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

我的 VBScript 代码:

' 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

我的批处理文件:

@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

日志文件

[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 -- 

我可以在日志文件中看到,如果路径不包含空格,则批处理文件会收到完整路径,否则会被截断。 或者,有没有办法在构建 MSI 安装程序时直接将参数传递给批处理文件?

尝试了以下解决方案,但没有用

  1. arguments = Chr(34) & targetDirectory & Chr(34) 并将参数传递给批处理文件

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

似乎存在阻止在参数中使用双引号的错误。 你可以试试

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

其中 %1 将用双引号作为 "D:\New folder\batch files\".

接收

或者,您可以发送带有替换空格的参数

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

然后在批处理文件中替换回来

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