2015-09-10 127 views
2

我的VBScript不顯示任何我執行的命令的結果。我知道命令被執行,但我想捕獲結果。WScript.Shell.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 

但DOS不打印任何結果。我如何捕獲StdOutStdErr

回答

4

WScript.Shell.Exec()返回立即,即使它啓動的過程沒有。如果您嘗試立即閱讀StatusStdOut,那裏不會有任何內容。

MSDN documentation建議使用以下循環:

Do While oExec.Status = 0 
    WScript.Sleep 100 
Loop 

這將檢查Status每100ms,直到它的變化。實質上,您必須等到過程完成,然後才能讀取輸出。

有了一些小的改動你的代碼,它工作正常:

Const WshRunning = 0 
Const WshFinished = 1 
Const WshFailed = 2 
strCommand = "ping.exe 127.0.0.1" 

Set WshShell = CreateObject("WScript.Shell") 
Set WshShellExec = WshShell.Exec(strCommand) 

Do While WshShellExec.Status = WshRunning 
    WScript.Sleep 100 
Loop 

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 
0

你應該在循環內部,以及後閱讀這兩個流。當你的進程是冗長的時候,當這個緩衝區不會被連續清空時,它會阻塞I/O緩衝區!