14
Set wshShell = WScript.CreateObject ("WSCript.shell")
wshshell.run "runas ..."

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

4

4 回答 4

28

您将希望使用 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
于 2011-05-20T14:10:38.557 回答
9

这是 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
于 2017-07-24T15:03:56.403 回答
3

BoffinBrain 的解决方案仍然不起作用,因为 exec.Status 不返回错误级别(运行时仅返回 0,完成时返回 1)。为此,您必须使用 exec.ExitCode(返回由使用 Exec() 方法运行的脚本或程序设置的退出代码。)。所以解决方案更改为

Option Explicit

Const WshRunning = 0
' Const WshPassed = 0    ' this line is useless now
Const WshFailed = 1

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.ExitCode = WshFailed Then
    output = exec.StdErr.ReadAll
Else
    output = exec.StdOut.ReadAll
End If

WScript.Echo output
于 2019-12-10T17:10:06.023 回答
-1
var errorlevel = new ActiveXObject('WScript.Shell').Run(command, 0, true)

第三个参数必须为true,errorlevel为返回值,判断是否为0。

于 2017-03-08T08:41:25.633 回答