我的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
WScript.Shell.Exec()
立即返回,即使它启动的进程没有返回。如果您尝试立即读取Status
或StdOut
,那里将没有任何内容。
MSDN文档建议使用以下循环:
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
应该在循环内和循环后读取两个流。当你的进程是冗长的,那么它将阻塞在I/O缓冲区,当这个缓冲区不会被连续清空!!
我认为Tomek的回答很好,但不完整。
下面是一个代码示例。
Private Sub ExecuteCommand(sCommand$)
Dim wsh As Object
Set wsh = CreateObject("WScript.Shell")
Dim oExec As Object, oOut As TextStream
'Exec the command
Set oExec = wsh.Exec(sCommand$)
Set oOut = oExec.StdOut
'Wait for the command to finish
While Not oOut.AtEndOfStream
Call Debug.Print(oOut.ReadLine)
Wend
Select Case oExec.Status
Case WshFinished
Case WshFailed
Err.Raise 1004, "EndesaSemanal.ExecuteCommand", "Error: " & oExec.StdErr.ReadAll()
End Select
End Sub