0
votes

I try to write a VBScript that will execute external programs and read output from the execution of the program. I use this code:

Option Explicit
Dim Title,ws,Command,Exec,FileExe,param1
FileExe = "ping.exe"
param1 = "127.0.0.1 "

MeHappy FileExe,param1

Function MeHappy(FileExe, param1)
    Dim Title, ws, Command, Exec
    Title = "Test "
    Set ws = CreateObject("wscript.Shell")
    command = "cmd /c Start "& FileExe &" "& param1 &">test.txt "
    Msgbox command, 64, Title
    Exec = ws.run(command, 0, True) 
End Function

I see that cmd is executed and returning output but redirecting file is always 0kb and is empty.

Also I managed to redirect output with this code :

Set WshShell = WScript.CreateObject("WScript.Shell")
Return = WshShell.Run("cmd /c ping.exe 127.0.0.1 > test.txt", 1, True)

and file is ok it containing output from ping.exe.

But I stumbled upon another problem when I tried to start other external programs. The external program that I was calling itself is calling another exe program, and I can't read the whole output.

For example, if I have test.exe, and that test.exe itself is calling another another exe file (for example test1.exe), and in that case I do not recieve whole output. I receive only output from test.exe because probably test.exe only is calling test1.exe and it ends not waiting for test1.exe or anything.

This I can check from Task Manager. I see that test.exe is finished with executing, and file with output is generated but test1.exe is still running and after finish there is not output in the file, but if I run regularly (without script) from cmd only example test.exe, I can see whole output from test and from test1.

With the first script if I execute test.exe I see whole output but redirect file is always empty, with second script I do not receive whole output only. External program is something that I do not control of.

Any suggestion how this can be managed?

1

1 Answers

0
votes

When in doubt, read the documentation.

Start
[...]
Starts a separate Command Prompt window to run a specified program or command.

Output in another window can't be redirected in the current window.

Change this:

command = "cmd /c Start "& FileExe &" "& param1 &">test.txt "

into this:

command = "cmd /c "& FileExe &" "& param1 &">test.txt"

and the problem will disappear.

Another option would be to start another CMD instance with the entire command (including the redirection) as a command string in (nested) double quotes:

command = "cmd /c start cmd /c """& FileExe &" "& param1 &">test.txt"""
'                       ^^^^^^^^^                                   ^^

As for capturing output from grandchild processes: that depends pretty much on how the process is started and how its output is actually generated. One thing you could try is bypassing the launcher and starting the grandchild process directly.