vbscript – WScript.Shell.Exec – read output from stdout

vbscript – WScript.Shell.Exec – read output from stdout

WScript.Shell.Exec() returns immediately, even though the process it starts does not. If you try to read Status or StdOut right away, there wont be anything there.

The MSDN documentation suggests using the following loop:

Do While oExec.Status = 0
     WScript.Sleep 100
Loop

This checks Status every 100ms until it changes. Essentially, you have to wait until the process completes, then you can read the output.

With a few small changes to your code, it works fine:

Const WshRunning = 0
Const WshFinished = 1
Const WshFailed = 2
strCommand = ping.exe 127.0.0.1

Set WshShell = CreateObject(WScript.Shell)
Set WshShellExec = WshShell.Exec(strCommand)

Do While WshShellExec.Status = WshRunning
     WScript.Sleep 100
Loop

Select Case WshShellExec.Status
   Case WshFinished
       strOutput = WshShellExec.StdOut.ReadAll()
   Case WshFailed
       strOutput = WshShellExec.StdErr.ReadAll()
 End Select

WScript.StdOut.Write(strOutput)  write results to the command line
WScript.Echo(strOutput)          write results to default output

You should read both streams INSIDE the loop as well as after it. When your process is verbose then it will block on the I/O buffer when this buffer will not be emptyfied succesively!!!

vbscript – WScript.Shell.Exec – read output from stdout

Leave a Reply

Your email address will not be published.