Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: VBScript
Expertise: Intermediate
Aug 13, 2004



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Launch a Process with the WshShell Exec Method

The WshShell Exec method can be used to launch a process. It returns an object that can be used to monitor execution and to access the stdin and stdout streams. The following function uses it to launch a command line and return it's output, with a timeout parameter:

Function ExecCommandLine (ByVal MyCmd,ByVal TimeOut)
  'Execute MyCmd and return the content of the std output stream.
  'The process is terminated if it exceed TimeOut in seconds (approximation)
  'Timeout is effective only if greater then zero.
  Dim WSHShell,Process,LoopCount,ReturnValue
  Set WSHShell = CreateObject("WScript.Shell")
  Set Process = WSHShell.Exec("cmd /c " & MyCmd)
  LoopCount = 0
  Do 'Control loop
    wscript.Sleep 100
   If TimeOut > 0 Then LoopCount = LoopCount + 1
  Loop Until (Process.Status <> 0) Or (LoopCount > TimeOut * 10)
  If Process.Status = 0 Then 'Timeout occured
    ReturnValue = "[Process terminated after timeout!]" & VbCrLf 
    ReturnValue = "[Process completed]" & VbCrLf  
  End If
  ExecCommandLine = ReturnValue &  Process.StdOut.ReadAll
  Set WSHShell = Nothing
  Set Process = Nothing
End Function
Stephane Courcy-Poitras
Thanks for your registration, follow us on our social networks to keep up-to-date