Wednesday, April 25, 2012

StdIn,StdErr and stdout Property (WshScriptExec)

StdErr Property (WshScriptExec):
Exposes the stdin input stream of the Exec object.
Object

    WshScriptExec object.
 
 Object.StdIn

Use the StdIn property to pass data to a process started using Exec.
The following code starts a batch file and waits for the user input prompt. After entering the needed data through the StdIn stream, the batch file will be able to complete.

Dim WshShell, oExec, input
Set WshShell = CreateObject("WScript.Shell")
Set oExec    = WshShell.Exec("test.bat")
input = ""

Do While True

     If Not oExec.StdOut.AtEndOfStream Then
          input = input & oExec.StdOut.Read(1)
          If InStr(input, "Press any key") <> 0 Then Exit Do
     End If
     WScript.Sleep 100
Loop

oExec.StdIn.Write VbCrLf

Do While oExec.Status <> 1
     WScript.Sleep 100
Loop

StdOut Property (WshScriptExec):

Exposes the write-only stdout output stream of the Exec object.
  Object.StdOut

Object

    WshScriptExec object.

The StdOut property contains a read-only copy of any information the script may have sent to the standard output.

StdErr Property (WshScriptExec):
 Object.StdErr
Object

    WshScriptExec object.

Use the StdErr property to retrieve data sent to the stderr stream from a process started with Exec.

The following code demonstrates the StdErr object by attempting to execute a non-existent command and displaying the results.
VBScript

Dim WshShell, oExec
Set WshShell = CreateObject("WScript.Shell")
Set oExec    = WshShell.Exec("%comspec% /c dire")

Function ReadAllFromAny(oExec)

     If Not oExec.StdOut.AtEndOfStream Then
          ReadAllFromAny = oExec.StdOut.ReadAll
          Exit Function
     End If

     If Not oExec.StdErr.AtEndOfStream Then
          ReadAllFromAny = "STDERR: " + oExec.StdErr.ReadAll
          Exit Function
     End If
    
     ReadAllFromAny = -1
End Function

Dim allInput, tryCount

allInput = ""
tryCount = 0

Do While True

     Dim input
     input = ReadAllFromAny(oExec)

     If -1 = input Then
          If tryCount > 10 And oExec.Status = 1 Then
               Exit Do
          End If
          tryCount = tryCount + 1
          WScript.Sleep 100
     Else
          allInput = allInput & input
          tryCount = 0
     End If
Loop

WScript.Echo allInput




No comments: