我的VBScript没有显示我执行的任何命令的结果。我知道命令已执行但我想捕获结果。
我已经测试过很多方法,例如:
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
但它不打印任何结果。如何捕获StdOut
和StdErr
?
答案 0 :(得分:8)
WScript.Shell.Exec()
会立即返回 ,即使它启动的过程没有。如果您尝试立即阅读Status
或StdOut
,则不会有任何内容。
MSDN documentation建议使用以下循环:
Do While oExec.Status = 0
WScript.Sleep 100
Loop
每隔100毫秒检查一次Status
,直到它发生变化。基本上,您必须等到该过程完成,然后您才能读取输出。
对代码进行一些小的更改,它可以正常工作:
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
答案 1 :(得分:1)
您应该在循环内部以及之后读取两个流。如果你的进程是冗长的,那么当这个缓冲区不会被连续清空时它会阻塞I / O缓冲区!