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)
这是 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)