Capturing output from WshShell.Exec using Windows Script Host

后端 未结 5 578
无人及你
无人及你 2020-12-06 11:15

I wrote the following two functions, and call the second (\"callAndWait\") from JavaScript running inside Windows Script Host. My overall intent is to call one command line

5条回答
  •  悲哀的现实
    2020-12-06 11:52

    You cannot read from StdErr and StdOut in the script engine in this way, as there is no non-blocking IO as Code Master Bob says. If the called process fills up the buffer (about 4KB) on StdErr while you are attempting to read from StdOut, or vice-versa, then you will deadlock/hang. You will starve while waiting for StdOut and it will block waiting for you to read from StdErr.

    The practical solution is to redirect StdErr to StdOut like this:

    sCommandLine = """c:\Path\To\prog.exe"" Argument1 argument2"
    Dim oExec
    Set oExec = WshShell.Exec("CMD /S /C "" " & sCommandLine & " 2>&1 """)
    

    In other words, what gets passed to CreateProcess is this:

    CMD /S /C " "c:\Path\To\prog.exe" Argument1 argument2 2>&1 "
    

    This invokes CMD.EXE, which interprets the command line. /S /C invokes a special parsing rule so that the first and last quote are stripped off, and the remainder used as-is and executed by CMD.EXE. So CMD.EXE executes this:

    "c:\Path\To\prog.exe" Argument1 argument2 2>&1
    

    The incantation 2>&1 redirects prog.exe's StdErr to StdOut. CMD.EXE will propagate the exit code.

    You can now succeed by reading from StdOut and ignoring StdErr.

    The downside is that the StdErr and StdOut output get mixed together. As long as they are recognisable you can probably work with this.

提交回复
热议问题