Set wshShell = WScript.CreateObject ("WSCript.shell")
wshshell.run "runas ..."
如何获取结果并显示在 MsgBox 中
您将需要使用 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
这是 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
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
我认为这是最有道理的。它是 WshFinished,而不是 WshFailed。 我在输出出现时打印输出,而不是在最后打印。
Function ExecCommand(cmd)
Const WshRunning = 0
Const WshFinished = 1
Dim objWshShell : Set objWshShell = CreateObject("WScript.Shell")
Dim oExec : Set oExec = objWshShell.Exec(cmd)
Do
'sleep in the loop before reading pipelines and reading finished state
WScript.Sleep 50
' We must read these, or it seems to block execution after 700 lines out output,
' probably because VBScript is blocking the pipeline, because script completes if VBScirpt is stoped with Ctrl-C
While oExec.StdOut.AtEndOfStream <> True
WScript.StdOut.WriteLine(oExec.StdOut.ReadLine())
Wend
While oExec.StdErr.AtEndOfStream <> True
WScript.StdErr.WriteLine("ERROR: " & oExec.StdErr.ReadLine())
Wend
Finished = ( oExec.Status = WshFinished )
Loop Until Finished
WScript.StdOut.WriteLine("ExitCode: " & oExec.ExitCode)
WScript.Quit(oExec.ExitCode) ' Optionally sets exit-code and exits this VbScript (but does not stop the executing sub-shell)
End Function
一个很好的例子是:
ExecCommand "ping.exe 127.0.0.1 -n 3 -w 500"
查看错误输出:
ExecCommand "cmd /c Echo Test Error >&2"
var errorlevel = new ActiveXObject('WScript.Shell').Run(command, 0, true)
第三个参数必须为true,errorlevel将作为返回值,检查是否等于0。