How to Capture Command Output from VBScript at Window Scripting Host?


Under WSH (Windows Scripting Host), we can do a lot of tasks by using VBScript/JScript. The COM object WScript.Shell provides a useful method Exec that can be used to launch external command. We can also capture its output by StdOut.ReadLine() method.

1
2
3
4
5
6
7
8
9
10
11
' Execute program and 
' Read the output into a variable line by line
Dim ObjExec
Dim strFromProc
 
Set objShell = WScript.CreateObject("WScript.Shell")
Set ObjExec = objShell.Exec("cmd.exe /c dir")
Do
    strFromProc = ObjExec.StdOut.ReadLine()
    WScript.Echo "Output is: " & strFromProc
Loop While Not ObjExec.Stdout.atEndOfStream
' Execute program and 
' Read the output into a variable line by line
Dim ObjExec
Dim strFromProc

Set objShell = WScript.CreateObject("WScript.Shell")
Set ObjExec = objShell.Exec("cmd.exe /c dir")
Do
    strFromProc = ObjExec.StdOut.ReadLine()
    WScript.Echo "Output is: " & strFromProc
Loop While Not ObjExec.Stdout.atEndOfStream

The Stdout.atEndOfStream is used to test if it reaches the end of the output. Please note that we cannot mix StdIn.WriteLine and StdOut.ReadLine(), the interactive mode (both reading and writing) does not work.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
185 words
Last Post: C/C++ Coding Exercise - Tiny Echo Program
Next Post: C# LINQ: Possible Multiple Enumeration of IEnumerable (Resharper)

The Permanent URL is: How to Capture Command Output from VBScript at Window Scripting Host?

Leave a Reply