Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

My VBScript does not show the results of any command I execute. I know the command gets executed but I would like to capture the result.

I have tested many ways of doing this, for example the following:

Const WshFinished = 1
Const WshFailed = 2
strCommand = "ping.exe 127.0.0.1"

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

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

But it dos not print any results. How do I capture StdOut and StdErr?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

WScript.Shell.Exec() returns immediately, even though the process it starts does not. If you try to read Status or StdOut right away, there won't 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...