2015-09-10 128 views
2

我的VBScript不显示任何我执行的命令的结果。我知道命令被执行,但我想捕获结果。WScript.Shell.Exec - 从标准输出读取

我已经测试过这样做,例如下面的方法很多:

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 

但DOS不打印任何结果。我如何捕获StdOutStdErr

回答

4

WScript.Shell.Exec()返回立即,即使它启动的过程没有。如果您尝试立即阅读StatusStdOut,那里不会有任何内容。

MSDN documentation建议使用以下循环:

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

这将检查Status每100ms,直到它的变化。实质上,您必须等到过程完成,然后才能读取输出。

有了一些小的改动你的代码,它工作正常:

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 
0

你应该在循环内部,以及后阅读这两个流。当你的进程是冗长的时候,当这个缓冲区不会被连续清空时,它会阻塞I/O缓冲区!