devxlogo

Launch a Process with the WshShell Exec Method

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    Process.Terminate     ReturnValue = "[Process terminated after timeout!]" & VbCrLf   Else    ReturnValue = "[Process completed]" & VbCrLf    End If  ExecCommandLine = ReturnValue &  Process.StdOut.ReadAll  Set WSHShell = Nothing  Set Process = NothingEnd Function

devx-admin

Share the Post: