[dba-Tech] VbScript: Close applications and wait

Gustav Brock gustav at cactus.dk
Mon Mar 11 08:53:38 CDT 2013


Hi all

It took some efforts to find out how to do this: Close some applications by
their Windows title gracefully (=close, not terminate) and - but not before
they are closed - move on.
So here is how should you ever have the need :

<vbscript>
  Call KillTask("Some application title")
  Call KillTask("Some other application title")
  Call AwaitProcess("taskkill.exe")
  Call RunApp("<file name of registered application like: MyApp.mdb>")

' Supporting subfunctions
' -----------------------

Sub RunApp(ByVal strFile)

  Dim objShell

  Set objShell = CreateObject("WScript.Shell")
  objShell.Run Chr(34) & strFile & Chr(34), 1, False
  Set objShell = Nothing

End Sub


Sub KillTask(ByVal strWindowTitle)

  Dim objShell

  Set objShell = CreateObject("WScript.Shell")
  objShell.Run "TaskKill.exe /FI ""WINDOWTITLE eq " & strWindowTitle & """",
7, False
  Set objShell = Nothing

End Sub


Sub AwaitProcess(ByVal strProcess)

  Dim objSvc
  Dim strQuery
  Dim colProcess
  Dim intCount

  Set objSvc = GetObject("winmgmts:root\cimv2")
  strQuery = "select * from win32_process where name='" & strProcess & "'"

  Do 
    Set colProcess = objSvc.Execquery(strQuery)
    intCount = colProcess.Count
    If intCount > 0 Then
      ' Wait a split second before checking again.
      WScript.Sleep 300
    End If
  Loop Until intCount = 0

  Set colProcess = Nothing
  Set objSvc = Nothing

End Sub
</vbscript>

/gustav



More information about the dba-Tech mailing list