VBScript从Shell获得结果

Coc*_*Dev 6 vbscript scripting wsh windows-scripting

Set wshShell = WScript.CreateObject ("WSCript.shell")
wshshell.run "runas ..."
Run Code Online (Sandbox Code Playgroud)

如何获取结果并显示在MsgBox中

Nil*_*lpo 21

您将需要使用WshShell对象的Exec方法而不是Run.然后只需从标准流中读取命令行的输出.试试这个:

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
MsgBox strOutput                'write results in a message box
Run Code Online (Sandbox Code Playgroud)

  • 注意:这是异步的,因此您可能会在“Select Case”处看到不正确的“WshShellExec.Status” (2认同)
  • @Nilpo 我在运行任何东西时遇到了同样的问题。正如 rdev5 所说,“Exec”是异步的,因此在您第一次检查时“WshShellExec.Status”仍然为 0(正在运行)。您需要循环直到完成类似 `While WshShellExec.Status = 0 : WScript.Sleep 50 : Wend` 的内容,也许可以考虑编辑您的答案。 (2认同)

Bof*_*ain 8

这是 Nilpo 答案的修改版本,解决了WshShell.Exec异步问题。我们做一个忙循环,直到 shell 的状态不再运行,然后我们检查输出。将命令行参数-n 1更改为更高的值,使ping耗时更长,并看到脚本将等待更长的时间直到完成。

(如果有人对问题有真正的异步、基于事件的解决方案,请告诉我!)

Option Explicit

Const WshRunning = 0
Const WshFinished = 1
Const WshFailed = 2

Dim shell : Set shell = CreateObject("WScript.Shell")
Dim exec : Set exec = shell.Exec("ping.exe 127.0.0.1 -n 1 -w 500")

While exec.Status = WshRunning
    WScript.Sleep 50
Wend

Dim output

If exec.Status = WshFailed Then
    output = exec.StdErr.ReadAll
Else
    output = exec.StdOut.ReadAll
End If

WScript.Echo output
Run Code Online (Sandbox Code Playgroud)