2011-05-19 168 views
3
Set wshShell = WScript.CreateObject ("WSCript.shell") 
wshshell.run "runas ..." 

結果如何,我得到的結果,並顯示在一個MsgBox的VBScript正從殼牌

+0

定義「結果」。 Runas退出代碼?通過runas運行應用程序的退出代碼?應用程序的控制檯輸出? – Helen 2011-05-20 05:49:12

回答

16

你將要使用WshShell對象的Exec的方法,而不是運行。然後只需從標準流中讀取命令行的輸出即可。試試這個:

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 
+0

我們能用WshShell.Run做同樣的事情嗎? – Feytality 2016-01-05 17:48:04

+1

編號運行不提供對標準流的訪問。 – Nilpo 2016-01-05 22:25:32

+1

注意:這是異步的,因此您可能會在'Select Case'處看到不正確的'WshShellExec.Status' – rdev5 2016-05-25 23:12:14

-2
var errorlevel = new ActiveXObject('WScript.Shell').Run(command, 0, true) 

第三個參數必須是真實的,錯誤級別會返回值,檢查它是否等於0。

+0

不是VBScript;不(std)out(put)。 – 2017-03-08 11:02:41

+0

@ Ekkehard.Horner我在jscript中測試代碼,我認爲vbscript也可以 – netawater 2017-03-09 08:39:59

+0

從其他答案中可以看出,你的假設是錯誤的。 – 2017-03-09 14:49:39

0

這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