Windows批处理文件调用vbscript不会等待其完成 [英] Windows batch file calling vbscript doesn't wait for it finish

查看:105
本文介绍了Windows批处理文件调用vbscript不会等待其完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用于压缩某些文件的VBScript.从批处理文件中调用时,该批处理不会等待脚本完成,并且您似乎需要在vbscript中进行睡眠以使压缩有足够的时间,否则最终将得到一个空的或损坏的zip文件.有什么办法可以使cscript执行同步?

I have a VBScript that I am using to zip up some files. When called from a batch file, the batch doesn't wait for the script to finish, and you seem to need a sleep in the vbscript to give the zipping enough time, otherwise you end up with an empty or corrupt zip file. Is there any way to make the cscript execution be synchronous?

以下是脚本:

Set objArgs = WScript.Arguments
InputFolder = objArgs(0)
ZipFile = objArgs(1)
CreateObject("Scripting.FileSystemObject").CreateTextFile(ZipFile, True).Write "PK" & Chr(5) & Chr(6) & String(18, vbNullChar)
Set objShell = CreateObject("Shell.Application")
Set source = objShell.NameSpace(InputFolder).Items
objShell.NameSpace(ZipFile).CopyHere(source)
wScript.Sleep 30000

请注意,这是必需的,但最后要睡个好觉,因为我不知道实际压缩需要多长时间.然后批处理文件调用:

Notice the sleep at the end which is necessary, but hacky since I don't know how long the actual zipping will take. And the batch file call:

CScript //B zipCOM.vbs %TEMPZIPDIR% %ARCHIVEFILE%

推荐答案

zip文件夹操作是异步的.您需要等待代码结束.这是一种简单的方法:等待文件的锁定(通过压缩操作保留)被释放.

The zip folders operations are asynchronous. You need to wait for the code to end. This is a simple way to do it: wait until the lock on the file (hold by the zipping operation) has been released.

Option Explicit

Dim objArgs, InputFolder, ZipFile
    Set objArgs = WScript.Arguments
    InputFolder = objArgs.Item(0)
    ZipFile = objArgs.Item(1)

Dim fso
    Set fso = WScript.CreateObject("Scripting.FileSystemObject")
    fso.CreateTextFile(ZipFile, True).Write "PK" & Chr(5) & Chr(6) & String(18, vbNullChar)

Dim objShell, source
    Set objShell = CreateObject("Shell.Application")
    Set Source = objShell.NameSpace(InputFolder).Items

    objShell.NameSpace(ZipFile).CopyHere( source )

    ' Wait for the operation to start
    WScript.Sleep 3000

    ' Loop until the file can be written 
Dim objFile
    On Error Resume Next
    Do While True
        Err.Clear
        Set objFile = fso.OpenTextFile( ZipFile, 8, False )
        If Err.Number = 0 Then
            objFile.Close
            Exit Do
        End If
        WScript.Sleep 100
    Loop 

这篇关于Windows批处理文件调用vbscript不会等待其完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆