How to run an external program within the same window from a console-mode VBScript

VBScript 5.6 does not provide a function to execute a command line program within the same console-mode window as the script. If WshShell.Run is used to call the program, the program runs within a new window.

The Run function below can be used to run a program within the same window. RunCmd can be used to run an internal command processor command. The test program TestRun.vbs shows how to use these functions.

Example of how to call the test program:

cscript TestRun.vbs

File TestRun.vbs.zip



' Test program for Run and RunCmd functions.
' Author: Christian d'Heureuse (www.source-code.biz)

Option Explicit

Main

Sub Main
   Run "attrib"
   RunCmd "dir c:\*.sys"
   End Sub

' Runs an external program and pipes it's output to
' the StdOut and StdErr streams of the current script.
' Returns the exit code of the external program.
Function Run (ByVal cmd)
   Dim sh: Set sh = CreateObject("WScript.Shell")
   Dim wsx: Set wsx = Sh.Exec(cmd)
   If wsx.ProcessID = 0 And wsx.Status = 1 Then
      ' (The Win98 version of VBScript does not detect WshShell.Exec errors)
      Err.Raise vbObjectError,,"WshShell.Exec failed."
      End If
   Do
      Dim Status: Status = wsx.Status
      WScript.StdOut.Write wsx.StdOut.ReadAll()
      WScript.StdErr.Write wsx.StdErr.ReadAll()
      If Status <> 0 Then Exit Do
      WScript.Sleep 10
      Loop
   Run = wsx.ExitCode
   End Function

' Runs an internal command interpreter command.
Function RunCmd (ByVal cmd)
   RunCmd = Run("%ComSpec% /c " & cmd)
   End Function


Author: Christian d'Heureuse (www.source-code.biz, www.inventec.ch/chdh)
License: Free / LGPL
Index