WScript.Shell.Exec - 从标准输出读取输出 [英] WScript.Shell.Exec - read output from stdout
问题描述
我的 VBScript 不显示我执行的任何命令的结果.我知道命令会被执行,但我想捕获结果.
My VBScript does not show the results of any command I execute. I know the command gets executed but I would like to capture the result.
我已经测试了很多方法来做到这一点,例如:
I have tested many ways of doing this, for example the following:
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
?
But it dos not print any results. How do I capture StdOut
and StdErr
?
推荐答案
WScript.Shell.Exec()
返回立即,即使它启动的进程没有.如果您尝试立即读取 Status
或 StdOut
,那里将不会有任何内容.
WScript.Shell.Exec()
returns immediately, even though the process it starts does not. If you try to read Status
or StdOut
right away, there won't be anything there.
MSDN 文档建议使用以下循环:
Do While oExec.Status = 0
WScript.Sleep 100
Loop
每 100 毫秒检查一次 Status
直到它发生变化.本质上,您必须等到该过程完成,然后才能读取输出.
This checks Status
every 100ms until it changes. Essentially, you have to wait until the process completes, then you can read the output.
对您的代码进行一些小的更改,它可以正常工作:
With a few small changes to your code, it works fine:
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
这篇关于WScript.Shell.Exec - 从标准输出读取输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!