Vbscript WScript.Shell.Exec-从stdout读取输出
我的VBScript不显示我执行的任何命令的结果。我知道命令会被执行,但我想捕获结果 我已经测试了许多方法,例如:Vbscript WScript.Shell.Exec-从stdout读取输出,vbscript,Vbscript,我的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
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()
立即返回,即使它启动的进程没有返回。如果您尝试立即读取状态
或标准输出
,则不会有任何内容
建议使用以下循环:
Do While oExec.Status = 0
WScript.Sleep 100
Loop
这将每隔100毫秒检查一次状态
,直到状态发生变化。基本上,您必须等到流程完成,然后才能读取输出
只需对代码进行一些小的更改,即可正常工作:
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缓冲区,而该缓冲区不会连续清空 但是如何防止它在循环中阻塞呢?在有数据之前readAll()不会被阻塞吗?oExec是一个Shell对象,两个变量正在收集流内容。如果它太长,你可以把它扔了。。。。Do While oExec.Status=0 WScript.Sleep 1000如果不是oExec.StdErr.AtEndOfStream则vErrStr=vErrStr&oExec.StdErr.ReadAll End如果不是oExec.StdOut.AtEndOfStream则vOutStr=vOutStr&oExec.StdOut.ReadAll End如果循环