VBScript getting results from Shell
You will want to use the WshShell object's Exec method instead of Run. Then simply read the command line's output from the standard streams. Try this one:
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
MsgBox strOutput 'write results in a message box
This is a modified version of Nilpo's answer that fixes the issue with WshShell.Exec
being asynchronous. We do a busy-loop waiting until the shell's status is no longer running, and then we check the output. Change the command-line argument -n 1
to a higher value to make ping
take longer, and see that the script will wait longer until completion.
(If anyone has a true asynchronous, event-based solution to the problem, then please let me know!)
Option Explicit
Const WshRunning = 0
Const WshFinished = 1
Const WshFailed = 2
Dim shell : Set shell = CreateObject("WScript.Shell")
Dim exec : Set exec = shell.Exec("ping.exe 127.0.0.1 -n 1 -w 500")
While exec.Status = WshRunning
WScript.Sleep 50
Wend
Dim output
If exec.Status = WshFailed Then
output = exec.StdErr.ReadAll
Else
output = exec.StdOut.ReadAll
End If
WScript.Echo output
The solution of BoffinBrain still doesn't work, since exec.Status doesn't return an error level (returns just 0 while running and 1 when finished). For that purpose you must use exec.ExitCode (Returns the exit code set by a script or program run using the Exec() method.). So the solution changes to
Option Explicit
Const WshRunning = 0
' Const WshPassed = 0 ' this line is useless now
Const WshFailed = 1
Dim shell : Set shell = CreateObject("WScript.Shell")
Dim exec : Set exec = shell.Exec("ping.exe 127.0.0.1 -n 1 -w 500")
While exec.Status = WshRunning
WScript.Sleep 50
Wend
Dim output
If exec.ExitCode = WshFailed Then
output = exec.StdErr.ReadAll
Else
output = exec.StdOut.ReadAll
End If
WScript.Echo output