.VBS是否支持Hold-Wait程序范例?

时间:2012-12-18 19:44:26

标签: vbscript

可以在VBScript中实现以下编程结构。在ProgA开始之后,在执行某些行之后,它会生成两个说ProgB和ProgC的子句。当这些子.vbs完成时,那么父程序ProgA将会恢复它的执行并将完成其目标

                                    ProgA.VBS
                                        |
                 -------------------------------------------------
                 |                                               |
            ProgB.VBS                                        ProgC.VBS

感谢,

1 个答案:

答案 0 :(得分:3)

阅读WshShell对象(CreateObject("Wscript.Shell"))的.Run.Exec方法。请务必注意。bWaitOnReturn {。1}}参数以及WshScriptExec对象的 .Status (以及 .Exitcode )属性。 This answer包含.Run和.Exec。

的示例代码

<强>更新

a.vbs(不是生产质量代码!):

Option Explicit

Const WshFinished = 1

Dim goWSH : Set goWSH = CreateObject("WScript.Shell")

Dim sCmd, nRet, oExec

sCmd = "cscript .\b.vbs"
WScript.Echo "will .Run", sCmd
nRet = goWSH.Run(sCmd, , True)
WScript.Echo sCmd, "returned", nRet

sCmd = "cscript .\c.vbs"
WScript.Echo "will .Exec", sCmd
Set oExec = goWSH.Exec(sCmd)
Do Until oExec.Status = WshFinished : WScript.Sleep 100 : Loop
WScript.Echo sCmd, "returned", oExec.ExitCode

WScript.Echo "done with both scripts"
WScript.Quit 0

.Runs b.vbs:

MsgBox(WScript.ScriptName)
WScript.Quit 22

和.Execs c.vbs:

MsgBox(WScript.ScriptName)
WScript.Quit 33

输出:

cscript a.vbs
will .Run cscript .\b.vbs
cscript .\b.vbs returned 22
will .Exec cscript .\c.vbs
cscript .\c.vbs returned 33
done with both scripts

MsgBoxes将证明a.vbs等待b.vbs和c.vbs。

更新II - VBScript的多重处理((c)@DanielCook):

ax.vbs:

Option Explicit

Const WshFinished = 1

Dim goWSH : Set goWSH = CreateObject("WScript.Shell")

' Each cmd holds the command line and (a slot for) the WshScriptExec
Dim aCmds : aCmds = Array( _
    Array("cscript .\bx.vbs", Empty) _
  , Array("cscript .\cx.vbs", Empty) _
)
Dim nCmd, aCmd
For nCmd = 0 To UBound(aCmds)
    ' put the WshScriptExec into the (sub) array
    Set aCmds(nCmd)(1) = goWSH.Exec(aCmds(nCmd)(0))
Next
Dim bAgain
Do
    WScript.Sleep 100
    bAgain = False ' assume done (not again!)
    For Each aCmd In aCmds
        ' running process will Or True into bAgain
        bAgain = bAgain Or (aCmd(1).Status <> WshFinished)
    Next
Loop While bAgain
For Each aCmd In aCmds
    WScript.Echo aCmd(0), "returned", aCmd(1).ExitCode
Next

WScript.Echo "done with both scripts"
WScript.Quit 0

.Execs bx.vbs

Do
  If vbYes = MsgBox("Tired of this rigmarole?", vbYesNo, WScript.ScriptName) Then Exit Do
  WScript.Sleep 300
Loop
WScript.Quit 22

和cx.vbs:

Do
  If vbYes = MsgBox("Tired of this rigmarole?", vbYesNo, WScript.ScriptName) Then Exit Do
  WScript.Sleep 500
Loop
WScript.Quit 33

在没有进一步投入错误处理的情况下,不要在工作中这样做。