vbscript - WScript.Shell.Exec-从标准输出读取输出

标签 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.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

但是它不会打印任何结果。如何捕获StdOutStdErr

最佳答案

WScript.Shell.Exec()立即返回 ,即使它启动的过程没有。如果您尝试立即阅读StatusStdOut,那么那里什么也没有。

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

关于vbscript - WScript.Shell.Exec-从标准输出读取输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32492879/

相关文章:

javascript - VBScript 在加载时设置值

javascript - 如何将 VBScript 变量传递给 iMacros Javascript 宏?

c# - 我怎么知道在发送打印命令(按下 "Ctrl+P"按钮)后我应该等待 PrintDialog 多长时间?

excel - 在vbscript中将txt文件转换为excel

function - 调用存储在字符串变量中的函数名称?

asp-classic - 请求与 Request.QueryString

vbscript - 使用 VBScript 更改快捷方式中的目标

javascript - VBScript 到 Javascript 中的类型名称

validation - 如何使用 QTP/VBScript 将 PDF 中的内容提取到字符串中?

vbscript - 使用 VBS 更新注册表