Nilpo`s Scripting Secrets, Vol I - Wait for a program to end
(Page 3 of 4 )
There are three basic ways to wait for a program to terminate in WSH. If you are launching the program from your script, the first is by far the easiest.
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run "cleanmgr.exe",, True
The first example launches the Disk Cleanup Wizard using the WshShell object’s Run method. The Run method provides an optional third parameter that accepts a Boolean value indicating whether the script should wait until the program terminates before continuing. Setting this value to true will cause the script to wait until the Disk Cleanup Wizard finishes before moving on.
Do While WshShell.AppActivate("Disk Cleanup")
WScript.Sleep 1000 ' Wait while window is open
Loop
The second method is a little less reliable, but can be effective when monitoring programs that run in a window. The WScript Shell object provides an AppActivate method that is used to bring a specific window into focus. The method returns true if the window can be activated and false if not. Since this can only return false if the window doesn’t exist, it provides a handy workaround for monitoring programs that run in windows.
Do While IsRunning
WScript.Sleep 1000
Loop
Function IsRunning
Set objWMI = GetObject("winmgmts:.rootcimv2")
Set colProcesses = objWMI.ExecQuery("Select * From Win32_Process " & _
"Where Name = 'cleanmgr.exe'")
If colProcesses.Count > 0 Then
IsRunning = True
Else
IsRunning = False
End If
End Function
The third and final method relies on WMI’s ability to monitor the actual executable process. It queries WMI for the existence of a specific process and pauses execution based upon that finding. This method is extremely reliable and works effectively, although it’s not as efficient as the first method I showed you.
Next: More scripting secrets >>
More Windows Scripting Articles
More By Nilpo